#include <iostream>
#include <string.h>
using namespace std;
typedef struct zuobiao{
int x,y;
}Spot;
Spot *sequence;
void init(int **a,int **fuzhu,int m,int n){
sequence[0].x=0;
sequence[0].y=0;
int flag=1;
int count1=0;
fuzhu[0][0]=1;
int dx,dy;
while(flag){
int x=sequence[count1].x;
int y=sequence[count1].y;
int wether=1;
if(dx||dy){
if(wether&&y+dy<n&&x+dx<m&&y+dy>=0&&x+dx>=0){
if(fuzhu[x+dx][y+dy]==0){
fuzhu[x+dx][y+dy]=1;
count1++;
sequence[count1].x=x+dx;
sequence[count1].y=y+dy;
wether=0;
}
}
}
if(wether&&y+1<n&&fuzhu[x][y+1]==0){//east
fuzhu[x][y+1]=1;
count1++;
sequence[count1].x=x;
sequence[count1].y=y+1;
wether=0;
}
if(wether&&x+1<m&&fuzhu[x+1][y]==0){//south
fuzhu[x+1][y]=1;
count1++;
sequence[count1].x=x+1;
sequence[count1].y=y;
wether=0;
}
if(wether&&y-1>=0&&fuzhu[x][y-1]==0){//west
fuzhu[x][y-1]=1;
count1++;
sequence[count1].x=x;
sequence[count1].y=y-1;
wether=0;
}
if(wether&&x-1>=0&&fuzhu[x-1][y]==0){//north
fuzhu[x-1][y]=1;
count1++;
sequence[count1].x=x-1;
sequence[count1].y=y;
wether=0;
}
dx=sequence[count1].x-x;
dy=sequence[count1].y-y;
if(wether) flag=0;
}
}
int main()
{
int m,n;
cin>>m>>n;
int **a = new int*[m];
int **fuzhu = new int*[m];
for(int i=0;i<m;i++){
a[i]=new int[n];
fuzhu[i] =new int[n];
}
int count1=0;
for(int i=0;i<m;i++)
for(int j=0;j<n;j++){
a[i][j]=count1;
count1++;
fuzhu[i][j]=0;
}
sequence = new Spot[m*n];
init(a,fuzhu,m,n);
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
cout<<a[i][j]<<"\t";
cout<<"\n";
}
for(int i=0;i<m*n;i++){
int x=sequence[i].x;
int y=sequence[i].y;
cout<<a[x][y]<<" ";
}
return 0;
}
顺时针输出矩阵
最新推荐文章于 2022-07-04 16:36:49 发布