NYOJ 58 最少步数(广搜入门经典)
2016-07-15 20:01
204 查看
最少步数
时间限制:3000 ms | 内存限制:65535 KB难度:4
描述
这有一个迷宫,有0~8行和0~8列:
1,1,1,1,1,1,1,1,1
1,0,0,1,0,0,1,0,1
1,0,0,1,1,0,0,0,1
1,0,1,0,1,1,0,1,1
1,0,0,0,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,0,0,0,1
1,1,1,1,1,1,1,1,1
0表示道路,1表示墙。
现在输入一个道路的坐标作为起点,再如输入一个道路的坐标作为终点,问最少走几步才能从起点到达终点?
(注:一步是指从一坐标点走到其上下左右相邻坐标点,如:从(3,1)到(4,1)。)
输入第一行输入一个整数n(0<n<=100),表示有n组测试数据;
随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。
输出输出最少走几步。
样例输入
2 3 1 5 7 3 1 6 7
样例输出
12 11
广搜入门经典题,这个已经给出了迷宫就无需录入了,简单来说可以分为四步,
1:输入起点终点,
2:规定搜索的方向,
3:判断是否到达终点,没有到,继续搜索。
4:到达终点,输出最短距离。
#include<stdio.h> #include<string.h> int a[9][9]= {1,1,1,1,1,1,1,1,1, 1,0,0,1,0,0,1,0,1, 1,0,0,1,1,0,0,0,1, 1,0,1,0,1,1,0,1,1, 1,0,0,0,0,1,0,0,1, 1,1,0,1,0,1,0,0,1, 1,1,0,1,0,1,0,0,1, 1,1,0,1,0,0,0,0,1, 1,1,1,1,1,1,1,1,1, }; struct node { int x,y,s; }; int main() { struct node que [1000]; int book[10][10]; int next[4][2]={0,1,1,0,0,-1,-1,0}; int i,j,startx,starty,n,m,tx,ty,p,q,flag; scanf("%d",&n); while(n--) { memset(book,0,sizeof(book)); scanf("%d%d%d%d",&startx,&starty,&p,&q); if(startx==p&&starty==q)//这个特别坑,再原点不动直接输出0. { printf("0\n"); continue; } int head=1,tail=2; que[head].x=startx; que[head].y=starty; que[head].s=0; flag=0; while(tail>head) { for(i=0;i<4;i++) { tx=que[head].x+next[i][0]; ty=que[head].y+next[i][1]; if(tx<0||tx>8||ty<0||ty>8) continue; if(a[tx][ty]==0&&book[tx][ty]==0) { book[tx][ty]=1; que[tail].x=tx; que[tail].y=ty; que[tail].s=que[head].s+1; tail++; } if(tx==p&&ty==q) { flag=1; break; } } if(flag==1) break; head++; } printf("%d\n",que[tail-1].s); } return 0; }
相关文章推荐
- 面试题37:两个链表的第一个公共节点
- The MySQL server is running with the --read-only option so it cannot execute this statement
- codeforces 691F Couple Cover 暴力
- 2016.07.15【初中部 NOIP提高组 】模拟赛C
- Android中的ScrollView
- 大素数测试和大数素因子分解
- UVA 10719 Quotient Polynomial
- 跟Google 学代码: Building Apps with Multimedia(自定义相机和PrintHelper用法)
- 暑期-dp46道(2)
- UVA-537 Artificial Intelligence?
- onclicklistener到底怎么用?
- 简易的C/S系统(实现两个数的和)
- c# 访问SQL Server 其他会话正在使用事务的上下文
- 2016长乐夏令营 Day6
- 自我介绍-决心书
- 开发安全的web应用程序
- Java集合小结
- 【BZOJ-1336&1337】Alie最小圆覆盖 最小圆覆盖(随机增量法)
- IOS中json字符串原生数据请求&IOS跨平台AES128字符串加解密&AFNetworking框架的简单封装使用
- 软件构架、架构和框架的区别