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

来源:互联网 发布:2017年淘宝天猫电商节 编辑:程序博客网 时间:2024/06/13 22:10

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;} 


0 0