BFS/DFS模板

本文深入探讨了图遍历中的两种核心算法:广度优先搜索(BFS)和深度优先搜索(DFS),通过代码示例详细讲解了这两种算法的具体实现方式,并介绍了它们的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

BFS
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn=100;
bool vst[maxn][maxn]; //访问
int dir[4][2]={0,1,0,-1,1,0,-1,0};
struct State //状态
{
    int x,y; //坐标位置
    int Step_Counter;   //步数
};
State a[maxn];
bool CheckState(State s) 
{
    if(!vst[s.x][s.y]&&...) 
        return 1;
    else return 0;
}
void bfs(State st)
{
    queue<State>q;
    State now,next; 
    st.Step_Counter=0;
    q.push(st);
    vst[st.x][st.y]=1;
    while(!q.empty())
    {
        now=q.front();
        if(now==G) 
        {
            ... //exit
            return;
        }
        for(int i=0;i<4;i++)
        {
            next.x=now.x+dir[i][0];
            next.y=now.y+dir[i][1];
            next.Step_Counter=now.Step_Counter+1;
            if(CheckState(next))
            {
                q.push(next);
                vst[next.x][next.y]=1;
            }
        }
        q.pop();
    }
    return;
}
int main()
{
    .....
    return 0;
}
DFS
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
const int maxn=100;
bool vst[maxn][maxn];
int map[maxn][maxn];
int dir[4][2]={0,1,0,-1,1,0,-1,0};
bool CheckEdge(int x,int y)
{
    if(!vst[x][y]&&...)
        return 1;
    else return 0;
}
void dfs(int x,int y)
{
    vst[x][y]=1;
    if(map[x][y]==G)
    {
        .....
        return;
    }
    for(int i=0;i<4;i++)
    {
        if(CheckEdge(x+dir[i][0],y+dir[i][1]))
            dfs(x+dir[i][0],y+dir[i][1]);
    }
    return;
}
int main()
{
    .....
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值