题目链接:54. 螺旋矩阵
进阶题目:59. 螺旋矩阵 II
相同题目:剑指 Offer 29. 顺时针打印矩阵,这里简单难度
两题会做一题,则另外一题就会做
我是先做了59再做54的,所以这题比较快
class Solution {
public:
vector spiralOrder(vector>& matrix) {
int maxNum = matrix.size() * matrix[0].size();
int curNum = 0;
int i = 0;
int j = 0;
vector v;
vector> directions = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} }; // 右下左上
int directionIndex = 0;
while (curNum < maxNum) {
v.push_back(matrix[i][j]);
curNum++; //计数
matrix[i][j] = 0; //标记走过的
//判断是否转向
int next_i = i + directions[directionIndex][0];
int next_j = j + directions[directionIndex][1];
if (next_i < 0 || next_i >= matrix.size() || next_j < 0 || next_j >= matrix[0].size() || matrix[next_i][next_j] == 0) {
directionIndex = (directionIndex + 1) % 4; // 顺时针旋转至下一个方向
}
i = i + directions[directionIndex][0];
j = j + directions[directionIndex][1];
}
return v;
}
};



