面试题29:顺时针打印矩阵(C++)

题目地址https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

题目示例

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

解题思路

分析题目发现,这是一个走迷宫的问题,所以我们设置上下左右四个方位边界,然后根据边界进行循环打印,每打印一次,判断一次边界值,并将结果保存在res中。

  • 从左向右遍历,上边界top++,判断上边界是否超出下边界,即top>bottom
  • 从上往下遍历,右边界right--,判断右边界是否超过左边界,即right<left
  • 从右向左遍历,下边界bottom--,判断下边界是否超过上边界,即bottom<top
  • 从下往上遍历,左边界left++,判断左边界是否超过右边界,即left>right

程序源码

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
      //Step1:判空操作
      if(matrix.size() == 0 || matrix[0].size() == 0) return {};
      vector<int> res;
      //Step2:初始化上、下、左、右四个方位边界值
      int top = 0;
      int bottom = matrix.size() - 1;
      int left = 0;
      int right = matrix[0].size() - 1;
      while(1)
      {
          //Step3:从左到右遍历
          for(int i = left;i <= right; i++){
              res.push_back(matrix[top][i]);
          }
          //top移动至下一行,并进行边界检测
          top++;
          if(top > bottom ) break;

          //Step4:从上到下遍历
          for(int i = top;i <= bottom; i++){
              res.push_back(matrix[i][right]);
          }
          //right左移,并进行边界检测
          right--;
          if(left > right) break;
          
          //Step5:从右往左遍历
          for(int i = right;i >= left; i--){
              res.push_back(matrix[bottom][i]);
          }
          //bottom行上移,并进行边界检测
          bottom-- ;
          if(bottom < top) break;

          //Step6:从下往上遍历
          for(int i = bottom; i >= top; i--){
              res.push_back(matrix[i][left]);
          }
          //left右移,并进行边界检测
          left++;
          if(left > right) break;
      }
      return res;
    }
};

参考文章

https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/solution/cgen-sui-da-lao-de-bu-fa-by-xi-wang-ba/

https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/solution/mian-shi-ti-29-shun-shi-zhen-da-yin-ju-zhen-she-di/

猜你喜欢

转载自www.cnblogs.com/wzw0625/p/12556960.html