I:
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].
按顺时针取序列,因为序列不一定是正矩阵,所以需要每取完一个方向要当即--或++,并做判断是否需要再取下一个方向。
当取完left->right,需要top++表明上一行已取完,top->bottom需right--,right->left需先判断top<=bottom避免只有单行重复取了上行,而后bottom++,bottom->top需先判断left<=right避免重复取右列,而后left++;
class Solution {public: vector spiralOrder(vector> &matrix) { int m=matrix.size(); vector res; if(m==0) return res; int n=matrix[0].size(); int left=0,right=n-1,top=0,bottom=m-1; int i=0; while(left<=right&&top<=bottom) { for(i=left;i<=right;++i) res.push_back(matrix[top][i]); top++; for(i=top;i<=bottom;++i) res.push_back(matrix[i][right]); right--; if(top<=bottom){ for(i=right;i>=left;--i) res.push_back(matrix[bottom][i]); } bottom--; if(left<=right){ for(i=bottom;i>=top;--i) res.push_back(matrix[i][left]); } left++; } return res; }};
II:
Given an integer n, generate a square matrix filled with elements from 1 to n 2 in spiral order.
For example,
Given n =3,You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]] 注意左->右可遍历全,剩余两个方向遍历时需+1,最后一个方向掐头去尾避免重复遍历
class Solution {public: vector> generateMatrix(int n) { vector > result(n,vector (n)); if(n==0) return result; int step = 1; int left = 0; int right = n-1; int top = 0; int bottom = n-1; while(left<=right && top<=bottom) { // 左->右 for(int i=left;i<=right;i++) { result[top][i] = step; step++; } //上->下 for(int i=top+1;i<=bottom;i++) { result[i][right] = step; step++; } //右->左 for(int i=right-1;i>=left;i--) { result[bottom][i] = step; step++; } //下->上 for(int i=bottom-1;i>top;i--) { result[i][left] = step; step++; } left++; right--; top++; bottom--; } return result; }};