题目
原文:
Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
译文:
给定一个有向图,设计算法判断两结点间是否存在路径。
解答
根据题意,给定一个有向图和起点终点,判断从起点开始,是否存在一条路径可以到达终点。 考查的就是图的遍历,从起点开始遍历该图,如果能访问到终点, 则说明起点与终点间存在路径。稍微修改一下遍历算法即可。
代码如下(在BFS基础上稍微修改):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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;
}
完整代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#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上:
https://github.com/Hawstein/cracking-the-coding-interview
声明:自由转载-非商用-非衍生-保持署名 | 创意共享3.0许可证,转载请注明作者及出处
出处:http://hawstein.com/2012/12/25/4.2/