题目
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
解答
方案一:模拟打印矩阵的路径。
1、初始位置是矩阵的左上角,初始方向是向右,当路径超出界限或者进入之前访问过的位置时,则顺时针旋转,进入下一个方向。
2、判断路径是否进入之前访问过的位置需要使用一个与输入矩阵大小相同的辅助矩阵 visited,其中的每个元素表示该位置是否被访问过。当一个元素被访问时,将 visited 中的对应位置的元素设为已访问。
3、如何判断路径是否结束?由于矩阵中的每个元素都被访问一次,因此路径的长度即为矩阵中的元素数量,当路径的长度达到矩阵中的元素数量时,即为完整路径,于是将该路径返回。
#include "pch.h"
#include <vector>
#include <iostream>
using namespace std;
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();//矩阵的行
int 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;
}
};
方案二:按层模拟
可以将矩阵看成若干层,首先打印最外层的元素,其次打印次外层的元素,直到打印最内层的元素。
定义矩阵的第 kkk 层是到最近边界距离为 kkk 的所有顶点。例如,下图矩阵最外层元素都是第 111 层,次外层元素都是第 222 层,剩下的元素都是第 333 层。
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; row > top; row--) {
order.push_back(matrix[row][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return order;
}
}
参考: