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

//BFS
#include <queue>
#include <cstring>

using namespace std;

int n;
bool visited[n];
bool m[n][n];


bool hasRoot(int src,int dst)
{
    queue<int> q;
    memset(visited,false,sizeof(visited));
    
    q.push(src);
    while(!q.empty())
    {    int t = q.front();
        q.pop();
        if(t==dst) return true;
        for(int i=0;i<n;i++)
            if(m[t][i]&&!visited[i])
            {    q.push(i); 
                visited[i] = true;
            }    
    }
    return false;
}

//dfs
bool hasRoute = false;

void dfs(int i,int dst)
{    
    if(i==dst) hasRoute = true;
    
    visited[i] = true;
    for(int j=0;j<n;j++)
        if(m[i][j]&&!visited[j])
            dfs(j,dst);    
}

bool hasRoute(int src,int dst)
{    
    memset(visited,false,sizeof(visited));
    
    dfs(src,dst);
    return hasRoote;
}

 

 posted on 2013-08-07 14:41  xuanxu  阅读(207)  评论(0编辑  收藏  举报