最少步数 (bfs最短路径)
来源:互联网 发布:阿里云概念股创业板 编辑:程序博客网 时间:2024/04/28 15:58
这有一个迷宫,有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)分别表示起点的行、列,终点的行、列。 - 输出
- 输出最少走几步。
- 样例输入
23 1 5 73 1 6 7
- 样例输出
1211
思路:
上午学习的广搜 http://blog.csdn.net/qq_36238595/article/details/54945270
这题就是经典的广搜题了
代码:
#include<iostream>#include<algorithm>#include<queue>#include<string.h>using namespace std;int dir[4][2]={-1,0,1,0,0,-1,0,1};int v[9][9]={0};int mg[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 st { int x,y,c; };//queue<struct st> q; //如果是在外面创建队列则在下面操作的时候,每次要清空队列,以免下一组测试用例错误获取队头元素 void copy() { int i,j; for (i=0;i<9;i++) for (j=0;j<9;j++) v[i][j]=mg[i][j]; } int bfs(struct st s, struct st e) { queue<struct st> q; int i,j; struct st t; s.c=0; v[s.x][s.y]=1; q.push(s); while (!q.empty()) { s=q.front(); q.pop(); if (s.x==e.x&&s.y==e.y) { //while (!q.empty()) //{ //q.pop();// } return s.c; } for (i=0;i<4;i++) { t.x = s.x+dir[i][0]; t.y = s.y+dir[i][1]; //if (t.x<0||t.x>=9||t.y<0||t.y>=9||v[t.x][t.y]==1) // continue; if (v[t.x][t.y]==0) { t.c = s.c+1; v[t.x][t.y]=1; q.push(t); } } } } int main() { int n;struct st s,e; cin>>n; while (n--) { //memset(v,0,sizeof(v)); copy(); cin>>s.x>>s.y>>e.x>>e.y; cout<<bfs(s,e)<<endl; } return 0; }
0 0
- 最少步数 (bfs最短路径)
- 最少步数(BFS)
- 最少步数(bfs)
- 最少步数BFS
- 最少步数 【BFS】
- 迷宫最短路径的步数
- nyoj 58 最少步数(BFS)
- NYOJ58最少步数(bfs)
- ny 58 最少步数(bfs)
- nyoj 最少步数(BFS,DFS)
- nyoj 58 最少步数 (bfs)
- NYOJ - 最少步数【BFS】
- NYOJ58最少步数(BFS)
- 最少步数 bfs样板
- 58 最少步数【bfs】
- nyoj58最少步数bfs
- bfs最短路径
- BFS循环求迷宫最短路径及路径数
- 开发中关于神奇测试机的问题解决
- 了解JVM原理、结构;代码说明抽象概念
- Android:使用矢量图标(iconfont方式)
- #pragma预处理分析 和 struct 结构体大小的计算
- redmine中使用python按人员分组统计问题入excel的自编写案例
- 最少步数 (bfs最短路径)
- Java提高篇(三八)-----Java集合细节(四):保持compareTo和equals同步
- Oracle查询数据表数据很少却很慢
- ASP.NET中直接用C# 动态修改CSS样式
- Maven 环境的配置
- (15)Spring Boot使用Druid和监控配置【从零开始学Spring Boot】
- java 线程总结
- 使用软碟通制作系统启动盘
- 宏定义中使用do{}while(0)的好处