思路1:
- 沿右下左上一次访问矩阵(四个方向)
- 设立一个visit数组用于记录访问过的元素
- 当访问路径为矩阵元素的总数则停止访问
- 对矩阵size为0进行特殊处理,因为后续对order进行内存申请,并不申请为size为0的order
代码1:
class Solution {
private:
static constexpr int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0)
return {};
int rows = matrix.size(), columns = matrix[0].size();
vector<vector<bool>> visited(rows, vector<bool>(columns));
int total = rows * columns;
vector<int> order(total);
int row = 0, column = 0;
int directionIndex = 0;
for (int i = 0; i < total; i++) {
order[i] = matrix[row][column];
visited[row][column] = true;
int nextRow = row + directions[directionIndex][0];
int nextColumn = column + directions[directionIndex][1];
if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn])
directionIndex = (directionIndex + 1) % 4;
row += directions[directionIndex][0];
column += directions[directionIndex][1];
}
return order;
}
};
思路2:
- 对矩阵按层循环,每层都走右下左上
- 需要注意循环条件的约束,还有左上方向的约束
- 每个for的每个方向都得到达指针位置,即都有“=”,除了上没有
代码2:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0)
return {};
int rows = matrix.size(), columns = matrix[0].size();
vector<int> order;
int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++)
order.push_back(matrix[top][column]);
for (int row = top + 1; row <= bottom; row++)
order.push_back(matrix[row][right]);
if (left < right && top < bottom) {
for (int column = right - 1; column >= left; column--)
order.push_back(matrix[bottom][column]);
for (int row = bottom-1; row > top; row--)
order.push_back(matrix[row][left]);
}
left++;
right--;
top++;
bottom--;
}
return order;
}
};