原题链接:54. 螺旋矩阵
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res; //定义返回值
int n = matrix.size();
int m = matrix[0].size();
if(n == 0) return res;
int dx[4] = {0,1,0,-1},dy[4] = {1,0,-1,0}; //定义遍历的四个方向
bool sta[n][m]; //标记是否被遍历过
memset(sta, false, sizeof(sta));
for(int i = 0,x = 0,y = 0,d = 0;i < n * m;i++){
res.push_back(matrix[x][y]);
sta[x][y] = true;
int a = x + dx[d],b = y + dy[d];
if(a < 0 || a == n || b < 0 || b == m || sta[a][b]){
d = (d + 1) % 4;
a = x + dx[d],b = y + dy[d];
}
x = a,y = b;
}
return res;
}
};
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n,vector<int>(n, 0)); //定义返回值
bool sta[n][n];
memset(sta, false, sizeof(sta));
int dx[4] = {0,1,0,-1},dy[4] = {1,0,-1,0};
for(int i = 1,x = 0,y = 0,d = 0;i <= n * n; i++){
matrix[x][y] = i;
sta[x][y] = true;
int a = x + dx[d],b = y + dy[d];
if(a < 0 || a == n || b < 0 || b == n || sta[a][b]){
d = (d + 1) % 4;
a = x + dx[d],b = y + dy[d];
}
x = a,y = b;
}
return matrix;
}
};