Skip to content

Commit 3071a36

Browse files
authored
Update Find if Path Exists in Graph - Leetcode 1971.cpp
1 parent f2315d0 commit 3071a36

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

Find if Path Exists in Graph - Leetcode 1971/Find if Path Exists in Graph - Leetcode 1971.cpp

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
// Recursive DFS
2+
13
#include <vector>
24
#include <unordered_map>
35
#include <unordered_set>
@@ -34,3 +36,84 @@ class Solution {
3436
return false;
3537
}
3638
};
39+
40+
// Iterative DFS With Stack
41+
42+
#include <vector>
43+
#include <unordered_map>
44+
#include <unordered_set>
45+
#include <stack>
46+
47+
using namespace std;
48+
49+
class Solution {
50+
public:
51+
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
52+
if (source == destination) return true;
53+
54+
unordered_map<int, vector<int>> graph;
55+
for (const auto& edge : edges) {
56+
graph[edge[0]].push_back(edge[1]);
57+
graph[edge[1]].push_back(edge[0]);
58+
}
59+
60+
unordered_set<int> seen;
61+
stack<int> stack;
62+
stack.push(source);
63+
seen.insert(source);
64+
65+
while (!stack.empty()) {
66+
int node = stack.top();
67+
stack.pop();
68+
if (node == destination) return true;
69+
70+
for (int neighbor : graph[node]) {
71+
if (seen.find(neighbor) == seen.end()) {
72+
seen.insert(neighbor);
73+
stack.push(neighbor);
74+
}
75+
}
76+
}
77+
return false;
78+
}
79+
};
80+
81+
// BFS With Queue
82+
#include <vector>
83+
#include <unordered_map>
84+
#include <unordered_set>
85+
#include <queue>
86+
87+
using namespace std;
88+
89+
class Solution {
90+
public:
91+
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
92+
if (source == destination) return true;
93+
94+
unordered_map<int, vector<int>> graph;
95+
for (const auto& edge : edges) {
96+
graph[edge[0]].push_back(edge[1]);
97+
graph[edge[1]].push_back(edge[0]);
98+
}
99+
100+
unordered_set<int> seen;
101+
queue<int> queue;
102+
queue.push(source);
103+
seen.insert(source);
104+
105+
while (!queue.empty()) {
106+
int node = queue.front();
107+
queue.pop();
108+
if (node == destination) return true;
109+
110+
for (int neighbor : graph[node]) {
111+
if (seen.find(neighbor) == seen.end()) {
112+
seen.insert(neighbor);
113+
queue.push(neighbor);
114+
}
115+
}
116+
}
117+
return false;
118+
}
119+
};

0 commit comments

Comments
 (0)