BFS(带回溯路径) 典例 代码
来源:互联网 发布:lambda表达式java 编辑:程序博客网 时间:2024/06/03 21:23
BFS经典例题:
题目大意:给定一个点图,然后输出S到T的最短路径。
样例输入:
/*
5 6
###T#*
S#****
*##*##
******
*#*#*#
*/
样例输出:
(1,0)->(2,0)->(3,0)->(3,1)->(3,2)->(3,3)->(2,3)->(1,3)->(0,3)
AC代码如下:
#include<cstdio>#include<queue>#include<cstring>using namespace std; //如果没有这个,报错:'queue' does not name a type!const int N=100;char graph[N][N];int prex[N][N];int prey[N][N];int n,m;int sx,sy,tx,ty;queue <int> qx;queue <int> qy;int dirx[]={0,0,1,-1};int diry[]={1,-1,0,0};bool vis[N][N];bool check(int x,int y){ return (x>=0&&x<n&&y>=0&&y<m&&!vis[x][y]&&(graph[x][y]=='*'||graph[x][y]=='T'));//注意不要把'T'这个目的地给滤掉}void bfs(){ qx.push(sx); qy.push(sy); while(!qx.empty()) { int x=qx.front(); int y=qy.front(); qx.pop(); qy.pop(); for(int i=0;i<4;i++) { int nx=x+dirx[i]; int ny=y+diry[i]; if(check(nx,ny)) { vis[nx][ny]=1; prex[nx][ny]=x; prey[nx][ny]=y; if(graph[nx][ny]=='T') { return; } else { qx.push(nx); qy.push(ny); } } } }}void show(int x,int y){ if(x==-1) return ; show(prex[x][y],prey[x][y]); printf("(%d,%d)->",x,y);}int main(){ memset(prex,-1,sizeof(prex)); memset(prey,-1,sizeof(prey)); scanf("%d%d",&n,&m); for(int i=0;i<n;i++) { scanf("%s",graph[i]); for(int j=0;j<m;j++) { if(graph[i][j]=='S') { sx=i; sy=j; } else if(graph[i][j]=='T') { tx=i; ty=j; } } } bfs(); show(prex[tx][ty],prey[tx][ty]); printf("(%d,%d)\n",tx,ty); return 0;}
阅读全文
1 0
- BFS(带回溯路径) 典例 代码
- POJ 3414--Pots(BFS+回溯路径)
- bfs,dfs(回溯路径)倒水
- Pots(bfs+路径记录与回溯)
- BFS + 回溯路径 POJ
- POJ 3984-迷宫问题(BFS+回溯路径)
- poj3984迷宫问题(bfs带路径)
- poj3414Pots(bfs模拟数组 回溯路径)
- POJ---- Pots ----BFS的路径回溯问题
- POJ 2965-The Pilots Brothers' refrigerator(位运算+BFS+回溯路径)
- 迷宫BFS+递归回溯找爹打印路径
- FOJ 1205 小鼠迷宫问题【BFS+dfs回溯查找路径】
- bfs+预处理+路径回溯+字典序最小+hash
- 回溯法-bfs--迷宫问题的最短路径
- POJ 3414 Pots(BFS+回溯)
- poj 3984 迷宫问题(BFS+回溯)
- HDU 2510 符号三角形 NYOJ491 幸运三角形 (回溯||打表) 代码带解释
- HDU-1026 Ignatius and the Princess I(BFS) 带路径的广搜
- dom4j使用方法总结
- python
- 好记性不如烂笔头------使用Acra+Android-Email实现错误日志上传
- openwrt 实现tcp和串口的透传 编译固件设置ser2net
- Android 自定义view绘制折线图
- BFS(带回溯路径) 典例 代码
- Python学习之代码规范
- PAT (Advanced Level) Practise 1122 Hamiltonian Cycle (25)(哈密顿圈)
- 数据可视化四:Matlab数据可视化(三)
- Keyboard Row
- html文本链接
- MySQL两表关联的连接表该如何创建索引?
- C++作业六
- STL之set/multiset(二)