@@ -67,11 +67,11 @@ class Solution2 {
67
67
int bfs (const unordered_map<int , vector<int >>& adj,
68
68
const int start,
69
69
const int target) {
70
- unordered_set <int > q = {start};
70
+ vector <int > q = {start};
71
71
unordered_set<int > lookup;
72
72
int steps = 0 ;
73
73
while (!empty (q)) {
74
- unordered_set <int > new_q;
74
+ vector <int > new_q;
75
75
for (const auto & pos : q) {
76
76
if (pos == target) {
77
77
return steps;
@@ -84,7 +84,7 @@ class Solution2 {
84
84
continue ;
85
85
}
86
86
lookup.emplace (nei);
87
- new_q.emplace (nei);
87
+ new_q.emplace_back (nei);
88
88
}
89
89
}
90
90
q = move (new_q);
@@ -93,3 +93,43 @@ class Solution2 {
93
93
return -1 ;
94
94
}
95
95
};
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