|
| 1 | +// Recursive DFS |
| 2 | + |
1 | 3 | #include <vector>
|
2 | 4 | #include <unordered_map>
|
3 | 5 | #include <unordered_set>
|
@@ -34,3 +36,84 @@ class Solution {
|
34 | 36 | return false;
|
35 | 37 | }
|
36 | 38 | };
|
| 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