Skip to content

Commit e234027

Browse files
authored
Update find-if-path-exists-in-graph.cpp
1 parent 8fe7b6f commit e234027

File tree

1 file changed

+43
-3
lines changed

1 file changed

+43
-3
lines changed

C++/find-if-path-exists-in-graph.cpp

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,11 @@ class Solution2 {
6767
int bfs(const unordered_map<int, vector<int>>& adj,
6868
const int start,
6969
const int target) {
70-
unordered_set<int> q = {start};
70+
vector<int> q = {start};
7171
unordered_set<int> lookup;
7272
int steps = 0;
7373
while (!empty(q)) {
74-
unordered_set<int> new_q;
74+
vector<int> new_q;
7575
for (const auto& pos : q) {
7676
if (pos == target) {
7777
return steps;
@@ -84,7 +84,7 @@ class Solution2 {
8484
continue;
8585
}
8686
lookup.emplace(nei);
87-
new_q.emplace(nei);
87+
new_q.emplace_back(nei);
8888
}
8989
}
9090
q = move(new_q);
@@ -93,3 +93,43 @@ class Solution2 {
9393
return -1;
9494
}
9595
};
96+
97+
// Time: O(|V| + |E|)
98+
// Space: O(|V| + |E|)
99+
// dfs solution
100+
class Solution3 {
101+
public:
102+
bool validPath(int n, vector<vector<int>>& edges, int start, int end) {
103+
unordered_map<int, vector<int>> adj;
104+
for (const auto& edge : edges) {
105+
adj[edge[0]].emplace_back(edge[1]);
106+
adj[edge[1]].emplace_back(edge[0]);
107+
}
108+
return dfs(adj, start, end);
109+
}
110+
111+
private:
112+
int dfs(const unordered_map<int, vector<int>>& adj,
113+
const int start,
114+
const int target) {
115+
vector<int> stk = {start};
116+
unordered_set<int> lookup;
117+
while (!empty(stk)) {
118+
auto pos = stk.back(); stk.pop_back();
119+
if (pos == target) {
120+
return true;
121+
}
122+
if (!adj.count(pos)) {
123+
continue;
124+
}
125+
for (const auto& nei : adj.at(pos)) {
126+
if (lookup.count(nei)) {
127+
continue;
128+
}
129+
lookup.emplace(nei);
130+
stk.emplace_back(nei);
131+
}
132+
}
133+
return false;
134+
}
135+
};

0 commit comments

Comments
 (0)