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]
.
迭代递归都可以。
vector<int> spiralOrder(vector<vector<int> > &matrix) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<int> result; if(matrix.empty()||matrix[0].empty()) return result; int rows = matrix.size(); int cols = matrix[0].size(); int startx = 0,starty = 0; while(rows>2*startx&&cols>2*starty) { int endx = rows-1-startx; int endy = cols-1-starty; //top --一定ok的 for(int i=starty;i<=endy;i++) result.push_back(matrix[startx][i]); //right for(int i=startx+1;i<=endx;i++) result.push_back(matrix[i][endy]); //bottom if(endx>startx) { for(int i=endy-1;i>=starty;i--) result.push_back(matrix[endx][i]); } if(endy>starty) { //left for(int i=endx-1;i>startx;i--) result.push_back(matrix[i][starty]); } ++startx; ++starty; } return result; }
原文链接: https://www.cnblogs.com/summer-zhou/p/3243706.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/98960
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!