Ch4-2: find if 2 given vertices are connected in a directed map,BFS + JUST fix the DFS recursion

本文探讨了图遍历算法中的两种方法:广度优先搜索(BFS)与深度优先搜索(DFS),并详细分析了它们在解决节点间路径查找问题上的应用。通过具体的代码示例,展示了如何使用这两种算法来判断图中是否存在从一个节点到另一个节点的有效路径。

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

In this problem, there are 2 ways: BFS or DFS.

Hawstein used BFS:

#include 
#include 
#include 
#include 
using namespace std;

const int maxn = 100;
bool g[maxn][maxn], visited[maxn];
int n;
queue q;

void init(){
    memset(g, false, sizeof(g));
    memset(visited, false, sizeof(visited));
}
bool route(int src, int dst){
    q.push(src);
    visited[src] = true;
    while(!q.empty()){
        int t = q.front();
        q.pop();
        if(t == dst) return true;
        for(int i=0; i>n>>m;
    for(int i=0; i>u>>v;
        g[u][v] = true;
        if(i==0){cout<< "start of connections--" << endl;}
        cout<"<

input:

8 11
0 1
1 0
1 5
2 3
2 4
4 7
5 2
5 7
6 2
6 4
7 4

Output:

start of connections-
0->1
1->0
1->5
2->3
2->4
4->7
5->2
5->7
6->2
6->4
7->4
end of connections--
1
1
0
1

Here is the DFS solution but have errors in somecases, such as 0->3. The reason is that the case for v[i] didn't considered visited condition, then go to return false directly.

/*Given a directed graph, design an algorithm to find out whether there is a route between two nodes
*/
#include 
#define N 8
using namespace std;

int nextNbr(int g[][N], int i, int j){
    while((-1"<"<output:
1st case: 1
0: 0
1: 1
2: 0
3: 0
4: 0
5: 1
6: 0
7: 0
0
0: 0
1: 1
2: 0
3: 0
4: 1
5: 1
6: 0
7: 1


After I learned from zyli's code, The problem is fixed.

The reason is that the previous one fall into narrow path without go back so failed in some corner cases: for example: 0->3

Here is the final version of DFS with recursion.

/*Given a directed graph, design an algorithm to find out whether there is a route between two nodes
*/
#include 
#define N 8
using namespace std;

int nextNbr(int g[][N], int i, int j){
    while((-1"<"<J:  0, tim: 3
v[0]=0 
v[2]=0 
J:  1, tim: 5
v[5]=0 
J:  1, tim: 5
v[1]=0 
J:  1, tim: 5
1


Here is the sample analysis of the recursion for routeDFS(0,3)=1


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值