1
- #Uses python3
2
-
3
1
import sys
2
+ from queue import Queue
3
+
4
+ class MazeGraph :
5
+ def __init__ (self , n , adj ):
6
+ self .adj = adj
7
+ self .visited = [False ] * n
8
+
9
+ def visit (self , v ):
10
+ self .visited [v ] = True
11
+
12
+ def isVisited (self , v ):
13
+ return self .visited [v ]
14
+
15
+ # Time Complexity: O(|V|)
16
+ # Space Complexity: O(|V|)
17
+ # Good job! (Max time used: 0.03/5.00, max memory used: 9535488/536870912.)
18
+ def explore_dfs (self , u , v ):
19
+ if u == v :
20
+ return 1
21
+
22
+ self .visit (u )
23
+ for i in range (len (adj [u ])):
24
+ if not self .isVisited (adj [u ][i ]):
25
+ if self .explore_dfs (adj [u ][i ], v ) == 1 :
26
+ return 1
4
27
5
- def reach (adj , x , y ):
6
- #write your code here
7
- return 0
28
+ return 0
29
+
30
+ # Time Complexity: O(|V|)
31
+ # Space Complexity: O(|V|)
32
+ def explore_bfs (self , u , v , q ):
33
+ if u == v :
34
+ return 1
35
+
36
+ q .put (u )
37
+ while not q .empty ():
38
+ u = q .get ()
39
+ if u == v :
40
+ return 1
41
+ self .visit (u )
42
+
43
+ for i in range (len (adj [u ])):
44
+ if not self .isVisited (adj [u ][i ]):
45
+ q .put (adj [u ][i ])
46
+
47
+ return 0
48
+
49
+ def reach (adj , n , u , v , solution ):
50
+
51
+ aMaze = MazeGraph (n , adj )
52
+ if solution == 1 :
53
+ return aMaze .explore_dfs (u , v )
54
+ elif solution == 2 :
55
+ q = Queue (maxsize = n )
56
+ return aMaze .explore_bfs (u , v , q )
57
+ elif solution == 3 :
58
+ return 0
59
+ else :
60
+ return 0
8
61
9
62
if __name__ == '__main__' :
10
63
input = sys .stdin .read ()
@@ -18,4 +71,5 @@ def reach(adj, x, y):
18
71
for (a , b ) in edges :
19
72
adj [a - 1 ].append (b - 1 )
20
73
adj [b - 1 ].append (a - 1 )
21
- print (reach (adj , x , y ))
74
+
75
+ print (reach (adj , n , x , y , 2 ))
0 commit comments