Leetcode 54, Spiral Matrix, 难度medium
就是按照规定顺序输出一个矩形,用四个变量保存了边界,然后对每一条边进行循环读入,处理一下相应的边界问题,复杂度为O(n),遍历了一遍数组。
以下是代码:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(matrix.empty()) return {};
int count = matrix.size() * matrix[0].size();
vector<int> res;
int a = matrix[0].size() - 1, b = matrix.size() - 1, c = 0, d = 0;
int j;
for (j = 0; j < count; ) {
for (int i = c; i <= a; i++) { res.push_back(matrix[d][i]); j++;}
if(j == count) break;
for (int i = d + 1; i <= b; i++) { res.push_back(matrix[i][a]); j++;}
if(j == count) break;
for (int i = a - 1; i >= c; i--) { res.push_back(matrix[b][i]); j++;}
if(j == count) break;
for (int i = b - 1; i >= d + 1; i--) { res.push_back(matrix[i][c]); j++;}
if(j == count) break;
a--; b--; c++; d++;
}
return res;
}
};