首页 > 代码库 > [LeetCode] Spiral Matrix
[LeetCode] 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]
.
class Solution {public: vector<int> spiralOrder(vector<vector<int> > &matrix) { int m = matrix.size();//原矩阵m行n列 vector<int> res; if(m==0) return res; int n = matrix[0].size(); int rowStart=0,rowEnd=m-1,colStart=0,colEnd=n-1; int j=colStart,i=rowStart ; while(1) { for(j = colStart;j<=colEnd;j++) { res.push_back(matrix[i][j]); } j = j-1; if(res.size()==m*n) break; rowStart++; j = colEnd; for(i=rowStart;i<=rowEnd;i++) { res.push_back(matrix[i][j]); } colEnd--; i = rowEnd; for(j=colEnd;j>=colStart;j--) { res.push_back(matrix[i][j]); } j = j+1; if(res.size()==m*n) break; rowEnd--; j=colStart; for(i = rowEnd;i>=rowStart;i--) { res.push_back(matrix[i][j]); } colStart++; i = rowStart; }//end while return res; }};
[LeetCode] Spiral Matrix
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。