-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind-if-path-exists-in-graph.cpp
More file actions
81 lines (67 loc) · 1.63 KB
/
find-if-path-exists-in-graph.cpp
File metadata and controls
81 lines (67 loc) · 1.63 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// 1971. Find if Path Exists in Graph (4/27/55279)
// Runtime: 628 ms (31.19%) Memory: 161.30 MB (73.65%)
class Graph
{
public:
Graph(const int size)
{
adj.resize(size);
}
void addEdge(const int src, const int dst)
{
adj[src].push_back(dst);
}
std::vector<int> getNeighboors(const int node) const
{
return adj[node];
// if(adj.find(node) != adj.end())
// {
// return adj.at(node);
// }
// return {};
}
int getNumNodes() const
{
return adj.size();
}
private:
std::vector<std::vector<int>> adj;
// std::unordered_map<int, std::vector<int>> adj;
};
bool dfs(const Graph& graph, const int src, const int dst)
{
std::vector<bool> processed(graph.getNumNodes());
std::stack<int> frontier;
processed[src] = true;
frontier.push(src);
while (!frontier.empty())
{
const int current = frontier.top(); frontier.pop();
if(current == dst)
return true;
for (const auto next: graph.getNeighboors(current))
{
if(!processed[next])
{
processed[next] = true;
frontier.push(next);
}
}
}
return false;
}
class Solution {
public:
bool validPath(int n, vector<vector<int>>& edges, int source, int destination)
{
if(n == 1)
return true;
Graph g(n);
for(const auto& edge : edges)
{
g.addEdge(edge[0], edge[1]);
g.addEdge(edge[1], edge[0]);
}
return dfs(g, source, destination);
}
};