魔方
有一种高为n,宽为m的魔方,魔方上需要填上数字,规则如下:
数字由1开始从左上角按逆时针方向往里填,直到把所有格式都填满为止。
例如:
n=5, m=5,则魔方如下所示:
1 16 15 14 13
2 17 24 23 12
3 18 25 22 11
4 19 20 21 10
5 6 7 8 9
Input
有多组,每组一行,输入n,m( 0<n<10, 0<m<10)
输入0 0表示结束。
Output
输出魔方的内容。每个数字间只用一个空格格开,最后一个数字后面没有空格。其它地方也没有多余的空格。 每两个魔方之间用一个空行隔开,最后一个魔方后面没有多余的空行。 如果有多余的空格或空行,会wrong answer或者presentation error.
Sample Input
2 2
4 4
3 5
0 0
Sample Output
1 4
2 3
1 12 11 10
2 13 16 9
3 14 15 8
4 5 6 7
1 12 11 10 9
2 13 14 15 8
3 4 5 6 7
Source
TangQiao @ BNU
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int A[12][12];
void Put(int n,int m)
{
memset(A,0,sizeof(A));
int high = n,wide = m,Count = 0,I=0,J=1;
while(Count < n*m)
{
for(int i=1;i<=high&&Count<n*m;i++) A[++I][J] = ++Count ;
wide--;
for(int i=1;i<=wide&&Count<n*m;i++) A[I][++J] = ++Count ;
high--;
for(int i=1;i<=high&&Count<n*m;i++) A[--I][J] = ++Count ;
wide--;
for(int i=1;i<=wide&&Count<n*m;i++) A[I][--J] = ++Count ;
high--;
}
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
if(j!=m) printf("%d ",A[i][j]);
else printf("%d\n",A[i][j]);
}
}
int main()
{
int n,m,E=0;
while((cin>>n>>m)&&(n||m))
{
if(E++) putchar('\n');
Put(n,m);
}
return 0;
}