输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 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]
限制:
0 <= matrix.length <= 100
0 <= matrix[i].length <= 100来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/shun-shi-zhen-da-yin-ju-zhen-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我们的思路就是设置一个辅助二维容器,看当前的元素有没有被访问过,然后从二维矩阵的左上角开始顺时针遍历,每遍历一个,就在我们的辅助二维矩阵中标记,遇到越界或者已经遍历过就马上转向。
- class Solution {
- public:
- vector<int> spiralOrder(vector
int >>& matrix) { - vector<int> result;
- int rows=matrix.size();
- if(rows==0)
- {
- return result;
- }
- int cols=matrix[0].size();
- if(cols==0)
- {
- return result;
- }
- vector
int>> flag(rows,vector<int>(cols,0)); - int x=0;
- int y=0;
- while(flag[x][y]!=-1)
- {
- //向右遍历
- while(y
-1) - {
- result.push_back(matrix[x][y]);
- flag[x][y]=-1;
- y++;
- }
- //注意需要回退
- cout<
- if(y>0)
- {
- y--;
- }
-
- if(x
-1) - {
- x++;
- }
- //向下遍历
- while(x
-1) - {
- result.push_back(matrix[x][y]);
- flag[x][y]=-1;
- x++;
- }
- if(x>0)
- {
- x--;
- }
-
- if(y>0)
- {
- y--;
- }
- //向左遍历
- while(y>=0&&flag[x][y]!=-1)
- {
- result.push_back(matrix[x][y]);
- flag[x][y]=-1;
- y--;
- }
- if(x>0)
- {
- x--;
- }
- if(y
-1) - {
- y++;
- }
- //向上遍历
- while(x>=0&&flag[x][y]!=-1)
- {
- result.push_back(matrix[x][y]);
- flag[x][y]=-1;
- x--;
- }
- //如果没有越界的话,进入内圈
- if(x
-1) - {
- x++;
- }
- if(y
-1) - {
- y++;
- }
- }
- return result;
- }
- };