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]
.
如果下一步会遇到访问过的节点或者越界的节点,那么就转向。
转向按照右,下,左,上
1 class Solution { 2 public: 3 vector<int> spiralOrder(vector<vector<int> > &matrix) { 4 int m=matrix.size(); 5 if(m==0) return vector<int>(); 6 7 int n=matrix[0].size(); 8 9 vector<int> result(m*n); 10 11 vector<vector<bool> > visited(m,vector<bool>(n,false)); 12 13 vector<pair<int,int>> dir(4); 14 dir[0]=pair<int,int>(0,1); 15 dir[1]=pair<int,int>(1,0); 16 dir[2]=pair<int,int>(0,-1); 17 dir[3]=pair<int,int>(-1,0); 18 19 int i,j,k,count; 20 i=j=k=count=0; 21 22 while(1) 23 { 24 if(count==m*n) break; 25 26 result[count]=matrix[i][j]; 27 visited[i][j]=true; 28 29 if(i+dir[k].first>m-1||j+dir[k].second>n-1||i+dir[k].first<0||j+dir[k].second<0||visited[i+dir[k].first][j+dir[k].second]) 30 { 31 k=(++k)%4; 32 } 33 34 i+=dir[k].first; 35 j+=dir[k].second; 36 37 count++; 38 } 39 40 return result; 41 } 42 };
另外一种方法:
1 class Solution { 2 public: 3 vector<int> spiralOrder(vector<vector<int> > &matrix) { 4 int m=matrix.size(); 5 if(m==0) return vector<int>(); 6 7 int n=matrix[0].size(); 8 9 vector<int> result; 10 11 12 int x1=0; 13 int y1=0; 14 int x2=m-1; 15 int y2=n-1; 16 17 18 while(1) 19 { 20 21 for(int j=y1;j<=y2;j++) result.push_back(matrix[x1][j]); 22 x1++; 23 24 25 for(int i=x1;i<=x2;i++) result.push_back(matrix[i][y2]); 26 y2--; 27 28 29 if(x2+1!=x1) 30 for(int j=y2;j>=y1;j--) result.push_back(matrix[x2][j]); 31 x2--; 32 33 if(y1!=y2+1) 34 for(int i=x2;i>=x1;i--) result.push_back(matrix[i][y1]); 35 36 y1++; 37 38 if(result.size()==m*n) break; 39 } 40 41 return result; 42 } 43 44 };
时间: 2024-10-04 03:36:28