[LeetCode] 105: Spiral Matrix

来源:互联网 发布:布拉格之春 知乎 编辑:程序博客网 时间:2024/05/22 10:36
[Problem]

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].


[Solution]
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<int> res;

// invalid
if(matrix.size() == 0 || matrix[0].size() == 0)return res;

// initial bound
int upper = 0, bottom = matrix.size(), left = -1, right = matrix[0].size();
int i = 0, j = 0, direct = 0;// 0: right, 1: down, 2: left, 3: up
while(res.size() < matrix.size() * matrix[0].size()){
res.push_back(matrix[i][j]);
if(direct == 0){
if(j+1 == right){
right--;
i++;
direct = 1;
}
else{
j++;
}
}
else if(direct == 1){
if(i+1 == bottom){
bottom--;
j--;
direct = 2;
}
else{
i++;
}
}
else if(direct == 2){
if(j-1 == left){
left++;
i--;
direct = 3;
}
else{
j--;
}
}
else if(direct == 3){
if(i-1 == upper){
upper++;
j++;
direct = 0;
}
else{
i--;
}
}
}
return res;
}
};
说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击