您的位置:首页 > 其它

[模板]广度优先搜索BFS

2016-08-06 18:50 211 查看
BFS(广度优先搜索)适用于节点多,搜索树不深的情况;

学习博客:http://blog.csdn.net/raphealguo/article/details/7523411

DFS(深度优先搜索)适用于节点少,搜索树深的情况;

学习博客:http://rapheal.iteye.com/blog/1526863

具体情况具体分析,贴一个BFS模板:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <queue>
using namespace std;

const int N = 110;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
int a

;//原始数据
int f

;//记录是否走过
struct node{
int x;
int y;
int t;//步数
}S, T;
int BFS(int n)
{
queue<node>Q;
Q.push(S);
f[S.x][S.y] = 1;
while(!Q.empty())
{
node now = Q.front();
Q.pop();
for(int i = 0; i < 4; i++)
{
node New;
New.x = now.x + dx[i];
New.y = now.y + dy[i];
if(New.x<0 || New.y<0 || New.x>=n || New.y >=n || a[New.x][New.y]==1 || f[New.x][New.y])
continue;
New.t = now.t + 1;
Q.push(New);
/*
New.t = now.t + 1;
Q.push(New);
位置不能颠倒,否则New.t不能成功传进去
*/
f[New.x][New.y] = 1;
if(New.x==T.x && New.y==T.y)
return New.t;
}
}
return -1;
}
int main()
{
int n;
int i, j;

scanf("%d", &n);
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
scanf("%d", &a[i][j]);
S.x = 0;
S.y = 0;
S.t = 0;
T.x = n-1;
T.y = n-1;
int ans = BFS(n);

printf("%d", ans);
return 0;
}
/*
5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
----------
8
*/


BFS适用于

BFS在树的层次较深且子节点数较多的情况下,消耗内存十分严重。

广度优先搜索适用于节点的子节点数量不多,并且树的层次不会太深的情况。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: