您的位置:首页 > 其它

[LeetCode]Spiral Matrix

2015-11-22 23:13 351 查看
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) {
vector<int> ret;
if(matrix.size()==0)
return ret;
int colmin = 0;
int colmax = matrix.size()-1;
int rowmin = 0;
int rowmax = matrix[0].size()-1;
int i=0;
int j=0;
int flag = 0; //走路顺序
while(rowmin<=rowmax&&colmin<=colmax){
if(flag==0){
for(j=rowmin; j<=rowmax; ++j)
ret.push_back(matrix[i][j]);
j = rowmax; //漏掉这个会出错,因为j会走到rowmax+1
++colmin;
flag = 1;
continue;
}
if(flag == 1){
for(i=colmin; i<=colmax; ++i)
ret.push_back(matrix[i][j]);
i = colmax;
--rowmax;
flag = 2;
continue;
}
if(flag == 2){
for(j=rowmax; j>=rowmin;--j)
ret.push_back(matrix[i][j]);
j = rowmin;
--colmax;
flag = 3;
continue;
}
if(flag == 3){
for(i=colmax ; i>=colmin; --i)
ret.push_back(matrix[i][j]);
i = colmin;
++rowmin;
flag = 0;
continue;
}
}
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: