-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path26-09-23-FindIfPathExistsInGraph.cpp
More file actions
45 lines (36 loc) · 1.11 KB
/
26-09-23-FindIfPathExistsInGraph.cpp
File metadata and controls
45 lines (36 loc) · 1.11 KB
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
/*
Time: O(V+E);
Space: O(V);
https://leetcode.com/problems/find-if-path-exists-in-graph/description/
*/
class Solution {
public:
bool validPath(int n, vector<vector<int>>& edges, int source,
int destination) {
vector<unordered_set<int>> graph(n);
for (int i = 0; i < edges.size(); i++) {
graph[edges[i][0]].insert(edges[i][1]);
graph[edges[i][1]].insert(edges[i][0]);
}
return bfs(graph, source, destination);
}
bool bfs(vector<unordered_set<int>>& graph, int source, int destination) {
vector<bool> visited(graph.size(), false);
queue<int> toProcess;
toProcess.push(source);
while (!toProcess.empty()) {
source = toProcess.front();
visited[source] = true;
toProcess.pop();
if (destination == source) {
return true;
}
for (auto u : graph[source]) {
if (visited[u] == false) {
toProcess.push(u);
}
}
}
return false;
}
};