cpp: add «1971. Find if Path Exists in Graph»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
48cdf36d0f
commit
f3631deaca
1 changed files with 35 additions and 0 deletions
35
cpp/find-if-path-exists-in-graph.cpp
Normal file
35
cpp/find-if-path-exists-in-graph.cpp
Normal file
|
@ -0,0 +1,35 @@
|
|||
#include <vector>
|
||||
|
||||
struct Solution {
|
||||
using edges_t = std::vector<std::vector<int>>;
|
||||
|
||||
bool validPath(int n, const edges_t &edges, int source, int destination) {
|
||||
std::vector<bool> visited(n);
|
||||
visited[source] = true;
|
||||
|
||||
bool changed;
|
||||
do {
|
||||
changed = iterate(edges, visited);
|
||||
} while (changed && !visited[destination]);
|
||||
|
||||
return visited[destination];
|
||||
}
|
||||
|
||||
private:
|
||||
bool iterate(const edges_t &edges, std::vector<bool> &visited) {
|
||||
bool changed = false;
|
||||
|
||||
for (const auto &edge : edges) {
|
||||
auto [u, v] = std::tie(edge[0], edge[1]);
|
||||
if (visited[u] == visited[v]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
visited[u] = true;
|
||||
visited[v] = true;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
};
|
Loading…
Reference in a new issue