#include<bits/stdc++.h>
using namespace std;
int a[10][10]={0};
int b[10][10]={0};
//思路就是0123分别代表四个方向,根据状态对两个下标做改动
//再建立一个数组判断是否被访问过,如果遇到0就转向
int main()
{
int n,m;
cin>>m>>n;
int sum=m*n;
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
cin>>a[i][j];
b[i][j]=1;
}
int state=0;
int i=0,j=0;
while(sum){
if(state==0)
{
cout<<a[i][j]<<" ";
b[i][j]=0;
j++;
if(b[i][j]==0)
{
state=(state+1)%4;
j--;i++;
}
}
else if(state==1){
cout<<a[i][j]<<" ";
b[i][j]=0;
i++;
if(b[i][j]==0)
{
state=(state+1)%4;
i--;j--;
}
}
else if(state==2){
cout<<a[i][j]<<" ";
b[i][j]=0;
j--;
if(b[i][j]==0)
{
state=(state+1)%4;
j++;i--;
}
}
else if(state==3)
{
cout<<a[i][j]<<" ";
b[i][j]=0;
i--;
if(b[i][j]==0)
{
state=(state+1)%4;
i++;
j++;
}
}
sum--;
}
return 0;
}
螺旋矩阵c++
最新推荐文章于 2024-07-25 12:39:48 发布