Find if Path Exists in Graph LeetCode solution in C++

1
class Solution {
2
private:
3
unordered_map<int, vector<int>> adj;
4
unordered_map<int, bool> visited;
5

6
bool dfs(int node, int destination) {
7
visited[node] = true;
8
for (auto neighbour : adj[node]) {
9
if (!visited[neighbour]) {
10
if (neighbour == destination) return true;
11
if (dfs(neighbour, destination)) return true;
12
}
13
}
14
return false;
15
}
16

17
public:
18
bool validPath(int n, vector<vector<int>> &edges, int source, int destination) {
19
if (source == destination) return true;
20

21
for (auto edge : edges) {
22
adj[edge[0]].push_back(edge[1]);
23
adj[edge[1]].push_back(edge[0]);
24
}
25
return dfs(source, destination);
26
}
27
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0