Q4.2 Given a directed graph, design an algorithm to find out whether there is a route.

本文介绍了一种使用广度优先搜索(BFS)算法来判断有向图中两个节点间是否存在路径的方法。通过建立哈希表记录已访问节点并利用队列进行节点遍历,确保了搜索过程的有效性和正确性。

Q: Given a directed graph, design an algorithm to find out whether there is a route between two nodes.

A: 采用bfs, 同时利用哈希表保存当前节点是否已经被访问了。

如果节点i 和节点j 相连,并且j没有被访问过,那么节点j入栈,说明节点j可能是所求路径上的点。

就这样遍历,直到栈为空或者到达终点。

#include <iostream>
#include <queue>
#include <cmath>
using namespace std;

const int maxn = 10;
bool g[maxn][maxn], visited[maxn];
int n;
queue<int> 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; ++i)
            if(g[t][i] && !visited[i]){
                q.push(i);
                visited[i] = true;
            }
    }
    return false;
}
int main(){
    init();
    int m, u, v;
    cin>>n>>m;
    for(int i=0; i<m; ++i){
        cin>>u>>v;
        g[u][v] = true;
    }
    cout<<route(0, 6)<<endl;
    return 0;
}
	 


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值