魔方

来源:互联网 发布:淘宝拍卖股权真的吗 编辑:程序博客网 时间:2024/06/10 07:35
魔方
Description
有一种高为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<vector>
using namespace std;
void print(int n,int m)
{
 bool td=false;
 bool tr=false;
 bool tu=false;
 bool tl=false;
 int circle=0;
 
 int x,y;
 int i,j;
 int t[50][50];
 x=1;y=1;
 td=true;
  for(i=1;i<=n*m;i++)
  {
   if(td)
   {
    t[x++][y]=i;
    if(x==n+1-circle)
    {
     x--;
     td=false;
     tr=true;
    }
   }
   if(tr)
   {
    t[x][y++]=i;
    if(y==m+1-circle)
    {
     y--;
     tr=false;
     tu=true;
    }    
   }
   if(tu)
   {
    t[x--][y]=i;
    if(x==circle)
    {
     x++;
     tu=false;
     tl=true;
    }    
   }
   if(tl)
   {
    t[x][y--]=i;
    if(y==circle+1)
    {
     y++;
     x++;
     tl=false;
     td=true;
     circle++;
    }   
   }
  }
  for(i=1;i<n;i++)
  {
   {
    for(j=1;j<=m;j++)
    cout<<t[i][j]<<" ";
   }
   cout<<endl;
  }
  for(j=1;j<m;j++)
    cout<<t[i][j]<<" ";
  cout<<t[i][j]<<endl; 
}
int main()
{
 int n,m;
 int i;
 vector<int> nn,mm;
 while(cin>>n>>m)
 {
  if(n==0 && m==0) break;
  nn.push_back(n);
  mm.push_back(m);
 }
 
 for(i=0;i<nn.size()-1;i++)
 {
  print(nn[i],mm[i]);
  cout<<endl; 
 }
 print(nn[i],mm[i]);
 return 0;
}
原创粉丝点击