按右、下、左、上的方向顺序遍历矩阵,某方向无法继续有效访问时变换方向。
54. 螺旋矩阵
相似题:59. 螺旋矩阵 II
//54.螺旋矩阵代码
class Solution {
public:
//按右,下,左,上的顺序访问矩阵
const int movex[4]={0,1,0,-1};
const int movey[4]={1,0,-1,0};
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m=matrix.size();
int n;
if (m>0) n=matrix[0].size();
vector <int> ans;
ans.clear();
if (m==0) return ans;
int now=0;
int nowx=0;
int nowy=0;
int cnt=0;
bool used[m+5][n+5];
ans.push_back(matrix[0][0]);
memset(used,false,sizeof(used));
used[0][0]=true;
while (cnt<m*n-1){
cnt++;
if (nowx+movex[now]<0 || nowx+movex[now]>=m || nowy+movey[now]<0 || nowy+movey[now]>=n){
//变换方向
now++;
now%=4;
}
else if (used[nowx+movex[now]][nowy+movey[now]]){
//变换方向
now++;
now%=4;
}
used[nowx+movex[now]][nowy+movey[now]]=true;
nowx+=movex[now];
nowy+=movey[now];
ans.push_back(matrix[nowx][nowy]);
}
return ans;
}
};
//59. 螺旋矩阵 II代码
class Solution {
public:
const int movex[4]={0,1,0,-1};
const int movey[4]={1,0,-1,0};
vector<vector<int>> generateMatrix(int n) {
int nowx=0;
int nowy=0;
int now=0;
int cnt=0;
int used[n+5][n+5];
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
used[i][j]=0;
}
}
cnt++;
used[0][0]=cnt;
while (cnt<n*n){
cnt++;
if (nowx+movex[now]<0 || nowx+movex[now]>=n || nowy+movey[now]<0 || nowy+movey[now]>=n){
//变换方向
now++;
now%=4;
}
else if (used[nowx+movex[now]][nowy+movey[now]]>0){
//变换方向
now++;
now%=4;
}
nowx+=movex[now];
nowy+=movey[now];
used[nowx][nowy]=cnt;
}
vector<vector<int>> ans;
for (int i=0;i<n;i++){
vector<int> help;
help.clear();
for (int j=0;j<n;j++) help.push_back(used[i][j]);
ans.push_back(help);
}
return ans;
}
};