-
Notifications
You must be signed in to change notification settings - Fork 0
/
FindIfPathExistsInGraphSolved.cpp
47 lines (37 loc) · 1.05 KB
/
FindIfPathExistsInGraphSolved.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
class Solution {
public:
bool validPath(int n, vector<vector<int>>& edges, int source,
int destination) {
if (source == destination) {
return true;
}
// adjacency list
vector<int>* graph = new vector<int>[n];
for (int i = 0; i < edges.size(); i++) {
int u_i = edges[i][0];
int v_i = edges[i][1];
graph[u_i].push_back(v_i);
graph[v_i].push_back(u_i);
}
// DFS
stack<int> s;
bool* visited = new bool[n]();
visited[source] = true;
s.push(source);
while (!s.empty()) {
int v = s.top();
s.pop();
for (auto it = graph[v].begin(); it != graph[v].end(); ++it) {
int u = *it;
if (u == destination) {
return true;
}
if (!visited[u]) {
visited[u] = true;
s.push(u);
}
}
}
return false;
}
};