题解 | #螺旋矩阵#清晰易懂
螺旋矩阵
http://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31
vector<int> spiralOrder(vector<vector<int> > &matrix) { if(matrix.empty()) return {}; int a = matrix.size(); int b = matrix[0].size(); vector<int> result; int cicleNum = (min(a,b)+1)/2; //向下取整,代表循环几次 int left = 0,top=0; int right = matrix[0].size()-1, bottom = matrix.size()-1; while(cicleNum--){ //顺时针 for(int i = left;i<=right;i++)//从左到右 result.push_back(matrix[top][i]); for(int j = top+1;j<=bottom;j++)//从上到下 result.push_back(matrix[j][right]); for(int k = right-1;k>=left && top!=bottom;k--) //从右到左,注意 top!=bottom,防止重复 result.push_back(matrix[bottom][k]); for(int l = bottom-1;l>top && left!=right;l--) //从下到上,注意 left!=right,防止重复 result.push_back(matrix[l][left]); left++; right--; top++; bottom--; } return result; }