-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1971.FindIfPathExistsInGraph.cpp
More file actions
40 lines (37 loc) · 1.06 KB
/
1971.FindIfPathExistsInGraph.cpp
File metadata and controls
40 lines (37 loc) · 1.06 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
class Solution {
public:
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
// Preprocess edges.
set<pair<int, int>> edgePairs;
for (int i = 0; i < edges.size(); i++)
edgePairs.emplace(edges[i][0], edges[i][1]);
// Find valid path.
set<int> newPoints, activePoints;
activePoints.emplace(source);
while (!activePoints.empty()) {
for (const int point : activePoints) {
// Check if path found.
if (point == destination) return true;
// Find matching edges.
for (auto it = edgePairs.begin(); it != edgePairs.end(); ) {
if (it->first == point) {
// Add edge point to new points + remove edge from list.
newPoints.emplace(it->second);
it = edgePairs.erase(it);
} else if (it->second == point) {
// Add edge point to new points + remove edge from list.
newPoints.emplace(it->first);
it = edgePairs.erase(it);
} else {
it++;
}
}
}
// Update active points.
activePoints = newPoints;
newPoints.clear();
}
// Found not found.
return false;
}
};