给你一个n*m的矩阵,让你输出如下的数字矩阵:
01 06 05
02 03 04
如下截图:
就是这样,然后自己就写了一发:
代码贴出来供参考:
#include <stdio.h>
#define MAX 1000
using namespace std;
int maze[MAX][MAX];
int Update(int n,int m,int &sx,int &sy,int cnt,int sum)
{
if(n==1&&m==1)
{
maze[sx][sy]=cnt++;
return cnt;
}
for(int j=0;j<n;j++)
maze[sx++][sy]=cnt++;
if(cnt>sum)
return cnt;
sx--,sy++;
for(int j=0;j<m-2;j++)
maze[sx][sy++]=cnt++;
if(cnt>sum)
return cnt;
for(int j=0;j<n;j++)
maze[sx--][sy]=cnt++;
if(cnt>sum)
return cnt;
sx++,sy--;
for(int j=0;j<m-2;j++)
maze[sx][sy--]=cnt++;
return cnt;
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
int cnt = 1;
if(n==1)
{
for(int j=0;j<m;j++)
maze[0][j]=cnt++;
}
else if(m==1)
{
for(int i=0;i<n;i++)
maze[i][0]=cnt++;
}
else
{
int sx = 0,sy = 0;
int tn = n, tm = m;
while(cnt<=n*m)
{
cnt = Update(tn,tm,sx,sy,cnt,n*m);
sx++;
sy++;
tn-=2;
tm-=2;
}
}
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
printf("%02d%c",maze[i][j],j==m-1?'\n':' ');
}
return 0;
}
几组测试样例如下: