题目
原文:
Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
译文:
给定一个有向图,设计算法判断两结点间是否存在路径。
解答
根据题意,给定一个有向图和起点终点,判断从起点开始,是否存在一条路径可以到达终点。 考查的就是图的遍历,从起点开始遍历该图,如果能访问到终点, 则说明起点与终点间存在路径。稍微修改一下遍历算法即可。
代码如下(在BFS基础上稍微修改):
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;
}
完整代码如下:
#include <iostream>
#include <queue>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn = 100;
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(){
freopen("4.2.in", "r", stdin);
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;
fclose(stdin);
return 0;
}
全书题解目录:
Cracking the coding interview–问题与解答
全书的C++代码托管在Github上: