百度百科 BFS
来源:互联网 发布:c 游戏编程入门 编辑:程序博客网 时间:2024/05/16 11:18
BFS在求解最短路径或者最短步数上有很多的应用。
应用最多的是在走迷宫上。
单独写代码有点泛化,取来自九度1335闯迷宫[2]一例说明,并给出C++/Java的具体实现。
在一个n*n的矩阵里走,从原点(0,0)开始走到终点(n-1,n-1),只能上下左右4个方向走,只能在给定的矩阵里走,求最短步数。n*n是01矩阵,0代表该格子没有障碍,为1表示有障碍物。
int mazeArr[maxn][maxn]; //表示的是01矩阵
int stepArr[4][2] = {{-1,0},{1,0},{0,-1},{0,1}}; //表示上下左右4个方向
int visit[maxn][maxn]; //表示该点是否被访问过,防止回溯,回溯很耗时。
核心代码。基本上所有的BFS问题都可以使用类似的代码来解决。
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
struct
Node{
int
x;
int
y;
int
step;
Node(
int
x1,
int
y1,
int
step1):x(x1),y(y1),step(step1){}
};
int
BFS() {
Node node(0,0,0);
queue<Node> q ;
while
(!q.empty()) q.pop();
q.push(node);
while
(!q.empty()) {
node = q.front();
q.pop();
if
(node.x == n-1 && node.y == n-1) {
return
node.step;
}
visit[node.x][node.y] = 1;
for
(
int
i = 0; i < 4; i++) {
int
x = node.x + stepArr[i][0];
int
y = node.y + stepArr[i][1];
if
(x >= 0 && y >= 0 && x < n && y < n
&& visit[x][y] == 0 && mazeArr[x][y] == 0) {
visit[x][y] = 1;
Node next(x, y, node.step+1);
q.push(next);
}
}
}
return
-1;
}
http://acm.hdu.edu.cn/showproblem.php?pid=1242
1.天使可能有多个朋友,所以不能从朋友的位置开始着天使,只能是从天使找离他最近的朋友
2.题目要求的是找到一个用时最少的朋友,而不是步数最少
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
char a[201][201];
int m,n;
int i,j,k;
int visit[201][201];
int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
struct prison
{
int x;
int y;
int time;
};
int BFS(int x,int y)
{
queue <prison> q;
prison cu,ne;
memset(visit,0,sizeof(visit));
cu.x=x;
cu.y=y;
cu.time=0;
visit[cu.x][cu.y]=1;
q.push(cu);
while(q.empty()!=1)
{
cu=q.front();
q.pop();
for(int i=0;i<4;i++)
{
ne.x=cu.x+dir[i][0];
ne.y=cu.y+dir[i][1];
if(ne.x>0 && ne.x<=m && ne.y>0 && ne.y<=n && visit[ne.x][ne.y]==0 && a[ne.x][ne.y]!='#')
{
if(a[ne.x][ne.y]=='r')
{
return cu.time+1;
}
if(a[ne.x][ne.y]=='x')
{
ne.time=cu.time+2;
}
else
ne.time=cu.time+1;
visit[ne.x][ne.y]=1;
q.push(ne);
//cout<<ne.time<<endl;
}
}
}
return -1;
}
int main()
{
prison an;
while(scanf("%d%d",&m,&n)!=EOF)
{
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
cin>>a[i][j];
if(a[i][j]=='a')
{
an.x=i;
an.y=j;
}
}
}
int t;
t=BFS(an.x,an.y);
if(t==-1)
cout<<"Poor ANGEL has to stay in the prison all his life." <<endl;
else
cout<<t<<endl;
}
return 0;
}
0 0
- 百度百科 BFS
- 百科--Bfs
- 百度百科
- 百度百科
- 百度----百科
- 百度百科
- 百度百科
- 百度百科
- GPRS_百度百科
- 打嗝[摘自 百度百科]
- CAsyncSocket_百度百科
- crontab_百度百科
- Variant_百度百科
- MaskBlt_百度百科
- OpenGL_百度百科
- AnimateWindow_百度百科
- WCF百度百科
- KDE 百度百科
- 没有路由器,也可以很好的畅游无线网络
- 非常有用的15个Linux 服务器监控命令
- mysql高可用探究(二)Lvs+Keepalived+Mysql单点写入主主同步高可用方案
- Flex 亮度、对比度、饱和度和色相的设置
- SoC
- 百度百科 BFS
- Mac下 git 终端的utf-8 字符显示
- SQL 集合运算
- 最流行的Node.js快速开发框架大荟萃
- myeclipse中删除derby、设置默认项目字符集
- css手册
- Debian 7 安装 Wireshark。解决权限问题。
- JAVA SE1.0~1.3新特性整理
- [iOS]单例的创建方法