@@ -40,7 +40,7 @@ Explanation: There is no path from vertex 0 to vertex 5.
40
40
Please see [ 1971. Find if Path Exists in Graph (UnionFind Solution)] ( 1971-find-if-path-exists-in-graph-2.md ) .
41
41
42
42
## Intuition
43
- This graph may have multiple ** connected components** .
43
+ This graph may have multiple ** connected components** .
44
44
45
45
![ ] ( ../../images/graph_undirected_2.png )
46
46
@@ -68,6 +68,7 @@ We need to find if there is a path from `source` to `destination`. This question
68
68
* Space: ` O(n) ` .
69
69
70
70
## Python
71
+ ### Breadth-first search
71
72
``` python
72
73
class Solution :
73
74
def validPath (self , n : int , edges : List[List[int ]], source : int , destination : int ) -> bool :
@@ -93,6 +94,44 @@ class Solution:
93
94
return False
94
95
```
95
96
97
+ ### Depth-first search
98
+ ``` python
99
+ class Solution :
100
+ def __init__ (self ):
101
+ self .visited = set ()
102
+ self .found = False
103
+
104
+ def validPath (self , n : int , edges : List[List[int ]], source : int , destination : int ) -> bool :
105
+ if source == destination:
106
+ return True
107
+
108
+ self .destination = destination
109
+ self .vertex_to_vertices = defaultdict(list )
110
+
111
+ for vertex1, vertex2 in edges:
112
+ self .vertex_to_vertices[vertex1].append(vertex2)
113
+ self .vertex_to_vertices[vertex2].append(vertex1)
114
+
115
+ self .depth_first_search(source)
116
+
117
+ return self .found
118
+
119
+ def depth_first_search (self , vertex_ ):
120
+ if self .found:
121
+ return
122
+
123
+ for vertex in self .vertex_to_vertices[vertex_]:
124
+ if vertex == self .destination:
125
+ self .found = True
126
+ return
127
+
128
+ if vertex in self .visited:
129
+ continue
130
+
131
+ self .visited.add(vertex)
132
+ self .depth_first_search(vertex)
133
+ ```
134
+
96
135
## Java
97
136
``` java
98
137
// Welcome to create a PR to complete the code of this language, thanks!
0 commit comments