forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
route-between-two-nodes-in-graph.cpp
86 lines (77 loc) · 2.29 KB
/
route-between-two-nodes-in-graph.cpp
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Time: O(n)
// Space: O(n)
/**
* Definition for Directed graph.
* struct DirectedGraphNode {
* int label;
* vector<DirectedGraphNode *> neighbors;
* DirectedGraphNode(int x) : label(x) {};
* };
*/
// BFS
class Solution {
public:
/**
* @param graph: A list of Directed graph node
* @param s: the starting Directed graph node
* @param t: the terminal Directed graph node
* @return: a boolean value
*/
bool hasRoute(vector<DirectedGraphNode*> graph,
DirectedGraphNode* s, DirectedGraphNode* t) {
unordered_set<DirectedGraphNode *> visited_node;
visited_node.emplace(s);
return BFS(s, t, visited_node);
}
bool BFS(DirectedGraphNode* s, const DirectedGraphNode* t,
unordered_set<DirectedGraphNode *> &visited_node) {
queue<DirectedGraphNode *> q;
q.emplace(s);
while (!q.empty()) {
s = q.front();
q.pop();
if (s == t) {
return true;
}
// Add neighbors which are not visited into the queue
for (const auto& node: s->neighbors) {
if (visited_node.emplace(node).second) {
q.emplace(node);
}
}
}
return false;
}
};
// DFS
class Solution2 {
public:
/**
* @param graph: A list of Directed graph node
* @param s: the starting Directed graph node
* @param t: the terminal Directed graph node
* @return: a boolean value
*/
bool hasRoute(vector<DirectedGraphNode*> graph,
DirectedGraphNode* s, DirectedGraphNode* t) {
unordered_set<DirectedGraphNode *> visited_node;
visited_node.emplace(s);
return DFS(s, t, visited_node);
}
bool DFS(DirectedGraphNode* s, const DirectedGraphNode* t,
unordered_set<DirectedGraphNode *> &visited_node) {
if (s == t) {
return true;
}
// Search neighbors which are not visted
for (const auto& node: s->neighbors) {
if (visited_node.emplace(node).second) {
if (DFS(node, t, visited_node)) {
return true;
}
//visited_node.erase(node);
}
}
return false;
}
};