Spiral Matrix
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) {
const int m=matrix.size();
if(m==0)return vector<int>();
const int n=matrix[0].size();
if(n==0)return vector<int>();
vector<int> ret;
vector<vector<int> > visited(m,vector<int>(n,0));
int i=0,j=0;
int flag=1;
while(flag){
flag=0;
for(j;j<n && j>=0 && visited[i][j]!=1;j++){ // 向右访问
ret.push_back(matrix[i][j]);
visited[i][j]=1;
flag=1;
}
j--;i++;
for(i;i<m &&i>=0 && visited[i][j]!=1;i++){ // 向下访问
ret.push_back(matrix[i][j]);
visited[i][j]=1;
flag=1;
}
i--;j--;
for(j;j<n &&j>=0 && visited[i][j]!=1;j--){ // 向左访问
ret.push_back(matrix[i][j]);
visited[i][j]=1;
flag=1;
}
j++;i--;
for(i;i<m &&i>=0 && visited[i][j]!=1;i--){ // 向上访问
ret.push_back(matrix[i][j]);
visited[i][j]=1;
flag=1;
}
i++;j++;
}
return ret;
}
};
Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]此题相比I,更简单,思路一样。
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > ret(n,vector<int>(n,0));
if(n==0) return vector<vector<int> >();
int i=0,j=0;
int count=1,flag=1;
while(flag){
flag=0;
for(j;j<n && j>=0 && ret[i][j]==0;j++){
ret[i][j]=count++;
flag=1;
}
j--;i++;
for(i;i<n && i>=0 && ret[i][j]==0;i++){
ret[i][j]=count++;
flag=1;
}
i--;j--;
for(j;j<n && j>=0 && ret[i][j]==0;j--){
ret[i][j]=count++;
flag=1;
}
j++;i--;
for(i;i<n && i>=0 && ret[i][j]==0;i--){
ret[i][j]=count++;
flag=1;
}
i++;j++;
}
return ret;
}
};