您的位置:首页 > 其它

hrbust 1564 螺旋矩阵【dfs过】

2016-03-03 12:46 357 查看
螺旋矩阵
Time Limit: 1000 MSMemory Limit: 10240 K
Total Submit: 276(77 users)Total Accepted: 79(71 users)Rating: 





Special Judge: No
Description
对于给定的一个数n,要你打印n*n的螺旋矩阵。

比如n=3时,输出:

 1 2 3
 8 9 4
 7 6 5

Input
多组测试数据,每个测试数据包含一个整数n(1<=n<=32)
Output
对于每组测试数据,输出一个n*n的螺旋矩阵,定义在题目描述里。

在一组测试数据中,每个数占的字符宽度是该组数据中最大的数位数加1,比如3*3的螺旋矩阵,最大值是9,那么每个数就要占2个字符宽度。

两组测试数据之间用一个空行隔开。

Sample Input
1
2
3

Sample Output
1

1 2
4 3

1 2 3
8 9 4
7 6 5

好基友题解报告:http://blog.csdn.net/qq_33184171/article/details/50787788
水题一发,输出部分学到一个新知识,宽度控制可以这样来控制:

printf("%*d",len+1,ans[i][j]);
然后剩下的内容就比较简单了,我从坐标(1,1)出发 ,然后用1、2、3、4分别标记四个方向,当前方向一直走下去,如果碰到了边界或者是走过的地方,右转即可、

AC代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<cstdio>
#include<iostream>
using namespace std;
int ans[50][50];
int vis[50][50];
//1right,2down,3left,4up
int n;
int check(int x,int y)
{
if(x>=1&&x<=n&&y>=1&&y<=n&&vis[x][y]==0)return 1;
else return 0;
}
void dfs(int x,int y,int num,int cur)
{
//printf("%d %d\n",x,y);
ans[x][y]=num;
vis[x][y]=1;
if(cur==1)//1右、2下、3左、4上。
{
int xx=x;
int yy=y+1;
if(ans[xx][yy]||yy>n)//如果走到的地方已经有了数据或者是碰到了边界
{
xx=x+1;
yy=y;
if(check(xx,yy))//右转并且保证走的地方合法
dfs(xx,yy,num+1,2);
}
else
{
if(check(xx,yy))//继续走
dfs(xx,yy,num+1,cur);
}
}
if(cur==2)//1right,2down,3left,4up
{
int xx=x+1;
int yy=y;
if(ans[xx][yy]||xx>n)
{
xx=x;
yy=y-1;
if(check(xx,yy))
dfs(xx,yy,num+1,3);
}
else
{
if(check(xx,yy))
dfs(xx,yy,num+1,cur);
}
}
if(cur==3)//1right,2down,3left,4up
{
int xx=x;
int yy=y-1;
if(ans[xx][yy]||yy<1)
{
xx=x-1;
yy=y;
if(check(xx,yy))
dfs(xx,yy,num+1,4);
}
else
{
if(check(xx,yy))
dfs(xx,yy,num+1,cur);
}
}
if(cur==4)
{
int xx=x-1;
int yy=y;
if(ans[xx][yy])
{
xx=x;
yy=y+1;
if(check(xx,yy))
dfs(xx,yy,num+1,1);
}
else
{
if(check(xx,yy))
dfs(xx,yy,num+1,cur);
}
}
return ;
}
int main()
{
int f=0;
while(~scanf("%d",&n))
{
if(f!=0)
{
printf("\n");
}
f++;
int date=n*n;
int len=0;
while(date)
{
date/=10;
len++;
}
//printf("%d\n",len);
memset(vis,0,sizeof(vis));
memset(ans,0,sizeof(ans));
dfs(1,1,1,1);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
printf("%*d",len+1,ans[i][j]);
}
printf("\n");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息