题解 | #螺旋矩阵#
螺旋矩阵
https://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31
想清楚区别划分再去写,挺容易发懵出错得。
记住缩小区间得时候,
left++;right--;down--;up++;别整混了。
class Solution { public: vector<int> spiralOrder(vector<vector<int> > &matrix) { // vector<int> ans; int m=matrix.size(); if(m==0) return ans; int n=matrix[0].size(); if(n==0) return ans; int left=0; int right=n-1; int up=0; int down=m-1; //[1,2,3] //[4,5,6] //[7,8,9] //[1,2] //[3,4] while(left<=right && up<=down) { for(int i=left;i<=right;i++) ans.push_back(matrix[up][i]); up++; if(up>down) break; for(int i=up;i<=down;i++) ans.push_back(matrix[i][right]); right--; if(left>right) break; for(int i=right;i>=left;i--) ans.push_back(matrix[down][i]); down--; if(up>down) break; for(int i=down;i>=up;i--) ans.push_back(matrix[i][left]); left++; if(left>right) break; } return ans; } };