29. 顺时针打印矩阵

1
2
3
4
5
6
处理移动四个移动方向用:
vector<vector<int>> move{ {0, 1}, {1, 0}, {0, -1}, {-1, 0} };
或者:
static constexpr int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
标记矩阵的已访问元素和未访问元素用一个相同大小的bool矩阵visit
输入一个空matrix时,如果对其求matrix[0].size()会报错,因为没有matrix[0]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> order;

if (matrix.size() == 0 || matrix[0].size() == 0) {
return {};
}

int rowRange = matrix.size();
int colRange = matrix[0].size();
vector<vector<bool>> visit(rowRange, vector<bool>(colRange));
int total = rowRange * colRange;
vector<vector<int>> move{ {0, 1}, {1, 0}, {0, -1}, {-1, 0} };
int row = 0;
int col = 0;
int moveIndex = 0;
int nextRow, nextCol;
for (int i = 0; i < total; i++)
{
order.push_back(matrix[row][col]);
visit[row][col] = true;
nextRow = row + move[moveIndex][0];
nextCol = col + move[moveIndex][1];
if (nextRow >= rowRange || nextRow < 0 || nextCol >= colRange || nextCol < 0 || visit[nextRow][nextCol])
{
moveIndex = (moveIndex + 1) % 4;
}
row += move[moveIndex][0];
col += move[moveIndex][1];
}
return order;
}