[模板]广度优先搜索BFS

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[N][N];//原始数据
int f[N][N];//记录是否走过
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在树的层次较深子节点数较多的情况下,消耗内存十分严重。

广度优先搜索适用于节点的子节点数量不多,并且树的层次不会太深的情况。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值