面试题 04.01. 节点间通路
节点间通路。给定有向图,设计一个算法,找出两个节点之间是否存在一条路径。
示例1:
1 | 输入:n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]], start = 0, target = 2 |
示例2:
1 | 输入:n = 5, graph = [[0, 1], [0, 2], [0, 4], [0, 4], [0, 1], [1, 3], [1, 4], [1, 3], [2, 3], [3, 4]], start = 0, target = 4 |
提示:
- 节点数量n在[0, 1e5]范围内。
- 节点编号大于等于 0 小于 n。
- 图中可能存在自环和平行边。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/route-between-nodes-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Solution
- DFS
- BFS
Code
DFS
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
class Solution {
public:
bool findWhetherExistsPath(int n, vector<vector<int>>& graph, int start, int target) {
vector<int> visited(n,0);
vector<int> v[n];
for(int i=0;i<graph.size();i++){
v[graph[i][0]].push_back(graph[i][1]);
}
stack<int> s;
s.push(start);
visited[start] = 1;
int k, flag;
while(!s.empty()){
k = s.top(); flag = 0;
if(k == target) return true;
for(int j=0;j<v[k].size();j++){
if(visited[v[k][j]] == 0){
s.push(v[k][j]);
flag = 1;
visited[v[k][j]] = 1;
break;
}
}
if(!flag) s.pop();
}
return false;
}
};BFS
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
28class Solution {
public:
bool findWhetherExistsPath(int n, vector<vector<int>>& graph, int start, int target) {
vector<int> visited(n,0);
vector<int> v[n];
for(int i=0;i<graph.size();i++){
v[graph[i][0]].push_back(graph[i][1]);
}
queue<int> q;
q.push(start);
visited[start] = 1;
int k;
while(!q.empty()){
k = q.front();
if(k == target) return true;
q.pop();
for(auto t : v[k]){
if(visited[t]==0){
visited[t] = 1;
q.push(t);
}
}
}
return false;
}
};
- 本文标题:面试题 04.01. 节点间通路
- 本文作者:codeflysafe
- 创建时间:2020-04-04 15:09:44
- 本文链接:https://codeflysafe.github.io/2020/04/04/2020-04-04-面试题-04.01.-节点间通路/
- 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
评论