NYOJ 58 最少步数(BFS)
2015-07-30 23:29
288 查看
最少步数
描述这有一个迷宫,有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
#include<cstdio> #include<queue> #include<cstring> using namespace std; int sx,sy,ex,ey; int d[4][2]={1,0,0,1,-1,0,0,-1}; bool visit[9][9]; int G[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 point { int x; int y; int step; }; int bfs() { point init; init.x=sx; init.y=sy; init.step=0; queue<point>q; q.push(init); while(!q.empty()) { point node=q.front(); q.pop(); if(node.x==ex&&node.y==ey) return node.step; for(int i=0;i<4;i++) { point newnode; newnode.x=node.x+d[i][0]; newnode.y=node.y+d[i][1]; newnode.step=node.step+1; if(!G[newnode.x][newnode.y]&&visit[newnode.x][newnode.y]) q.push(newnode); visit[node.x][node.y]=false; } } } int main() { //freopen("in.txt","r",stdin); int t; scanf("%d",&t); while(t--) { memset(visit,true,sizeof(visit)); scanf("%d%d%d%d",&sx,&sy,&ex,&ey); int ans=bfs(); printf("%d\n",ans); } return 0; }
相关文章推荐
- 面向对象的设计原则
- http请求
- Android getActionBar() 为null解决方案
- poj 3104 二分答案
- poj 1364 King(差分约束)(中等)
- 数据库MySQL基础——增删查改
- V3.1管理经验总结分析
- 机试算法讲解: 第4题 某一天是星期几?
- Visual Studio 出现“无法解析的外部符号”错误
- QT在CT上的安装及运行
- 快速排序详解
- JDBC接口讲解与底层实现分析(上)
- 技术团队建设
- ABP领域层——领域事件(Domain events)
- redis配置文件redis.conf中文版
- [转]iOS 中几种定时器 - 控制了时间,就控制了一切
- PHP程序员的职业规划,走进PHP后端工程师的世界
- iOS开发系列--UITableView全面解析
- C++对象模型——Copy Constructor 的建构操作(第二章)
- Git常用命令(一)