Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
You should return [1,2,3,6,9,8,7,4,5]
.
这道题挺简单的,基本上算是一次性写出来的,就是设立一个对应的标志数组,然后按照螺旋的规则来遍历。
代码如下:
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> res; int height=matrix.size(); if( height==0) return res; int width=matrix[0].size(); vector<vector<int>> flag(height,vector<int>(width,1));//用来记录是否走过 int m=0; int n=0; flag[0][0]=0; res.push_back(matrix[0][0]); int step=1; while(step!= height* width) { while(n+1<width&&flag[m][n+1]) { flag[m][n+1]=0; res.push_back(matrix[m][n+1]); n+=1; step++; } while(m+1<height&&flag[m+1][n]) { flag[m+1][n]=0; res.push_back(matrix[m+1][n]); m+=1; step++; } while(n-1>=0&&flag[m][n-1]) { flag[m][n-1]=0; res.push_back(matrix[m][n-1]); n-=1; step++; } while(m-1>=0&&flag[m-1][n]) { flag[m-1][n]=0; res.push_back(matrix[m-1][n]); m-=1; step++; } } return res; } };
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
I写出来了的话,II就更简单了,在I上改一下就行了,代码如下:
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> flag(n,vector<int>(n,0));//用来记录是否走过 if(n==0) return flag; int height=0; int width=0; int step=1; flag[0][0]=1; while(step!= n*n) { while(width+1<n&&flag[height][width+1]==0) { width+=1; step++; flag[height][width]=step; } while(height+1<n&&flag[height+1][width]==0) { height+=1; step++; flag[height][width]=step; } while(width-1>=0&&flag[height][width-1]==0) { width-=1; step++; flag[height][width]=step; } while(height-1>=0&&flag[height-1][width]==0) { height-=1; step++; flag[height][width]=step; } } return flag; } };