hrbust 1564 螺旋矩阵【dfs过】
2016-03-03 12:46
357 查看
螺旋矩阵 | ||||||
| ||||||
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 |
水题一发,输出部分学到一个新知识,宽度控制可以这样来控制:
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"); } } }
相关文章推荐
- Quartz指南
- Unity热更新之C#反射动态获取类属性及方法
- Unity热更新之C#反射动态获取类属性及方法
- Android开发学习之Intent具体解释
- 高等数学:第十二章 微分方程(2)一阶线性非齐次微分方程、全微分方程、可降阶的微分方程
- Leet Code OJ 171. Excel Sheet Column Number [Difficulty: Easy]
- android中使用哪种方式解析XML比較好
- 常见Import错误
- Nginx入门笔记_第一篇
- Excel文件上传,解析,下载(三 创建文件和文件下载)
- html5前端图片压缩
- Quartz指南
- 高等数学:第十二章 微分方程(1)微分方程的概念,可分离变量的微分方程,齐次方程
- Linux install iperf3 record
- u盘在我的电脑中不显示
- TuShare(1):Python股票抓取工具TuShare
- hadoop之mapreduse 在Eclipse下的调试环境篇
- 阿里云
- POJ 1088(记忆化搜索)
- 机会网络路由学习之Controlled Routing