将一个二维矩阵,螺旋方式遍历。
Example 1:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
思考:本题的难点在于以螺旋的方式访问。需要考虑各个方向和是否访问过,何时旋转方向继续向前。
解法:
方法1:使用辅助空间记录是否已经访问过。
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.empty()) { return res;}
int rows = matrix.size();
int cols = matrix[0].size();
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
int len = rows * cols;
int r = 0, c = 0;
int j = 0;
int dr[4] = {0, 1, 0, -1};
int dc[4] = {1, 0, -1, 0};
for (int i = 0; i < len; ++i) {
res.push_back(matrix[r][c]);
visited[r][c] = true;
int n_r = r + dr[j];
int n_c = c + dc[j];
if ((n_r >= 0 && n_r < rows) && (n_c >= 0 && n_c < cols) && (!visited[n_r][n_c])) {
r = n_r;
c = n_c;
} else {
j = (j + 1) % 4;
r += dr[j];
c += dc[j];
}
}
return res;
}
方法2:直接遍历。需要注意while,for循环的比较运算符。
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.empty() || matrix[0].empty()) { return res; }
int r1 = 0;
int r2 = matrix.size() - 1;
int c1 = 0;
int c2 = matrix[0].size() - 1;
while(r1 <= r2 && c1 <= c2) {
for (int c = c1; c <= c2; ++c) { res.push_back(matrix[r1][c]); }
for (int r = r1 + 1; r <= r2; ++r) { res.push_back(matrix[r][c2]); }
if (r1 < r2 && c1 < c2) {
for (int c = c2 - 1; c > c1; --c) { res.push_back(matrix[r2][c]); }
for (int r = r2; r > r1; --r) { res.push_back(matrix[r][c1]); }
}
r1++;
r2--;
c1++;
c2--;
}
return res;
}