Skip to content

Commit c21e2ef

Browse files
author
Hamid Gasmi
committed
Issue #87 is completed with Bi-Directional BFS
1 parent b8e8303 commit c21e2ef

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import sys
2+
from queue import Queue
3+
import threading
4+
5+
class MazeGraph:
6+
7+
result = 0
8+
s = set()
9+
lock = threading.Lock()
10+
11+
def __init__(self, n, adj):
12+
self.adj = adj
13+
self.visited = [False] * n
14+
self.enqueued = [False] * n
15+
self.q = Queue(n)
16+
17+
def visit(self, v):
18+
self.visited[v] = True
19+
20+
if v in MazeGraph.s:
21+
MazeGraph.lock.acquire()
22+
MazeGraph.result = 1
23+
endThread = True
24+
MazeGraph.lock.release()
25+
else:
26+
MazeGraph.lock.acquire()
27+
MazeGraph.s.add(v)
28+
MazeGraph.lock.release()
29+
endThread = MazeGraph.result == 1
30+
31+
return endThread
32+
33+
def isVisited(self, v, visited):
34+
return visited[v]
35+
36+
def enqueue(self, v):
37+
if not self.enqueued[v]:
38+
self.q.put(v)
39+
self.enqueued[v] = True
40+
41+
# Time Complexity: O(|V| + |E|)
42+
# Space Complexity: O(|V|):
43+
def explore(self, u):
44+
self.enqueue(u)
45+
while not self.q.empty():
46+
u = self.q.get()
47+
if self.visit(u):
48+
return 1
49+
50+
for i in range(len(self.adj[u])):
51+
self.enqueue(self.adj[u][i])
52+
53+
return 0
54+
55+
def reach(n, edges, u, v):
56+
adj = [[] for _ in range(n)]
57+
for (a, b) in edges:
58+
adj[a - 1].append(b - 1)
59+
adj[b - 1].append(a - 1)
60+
61+
aMaze1 = MazeGraph(n, adj)
62+
aMaze2 = MazeGraph(n, adj)
63+
64+
t1 = threading.Thread(target=aMaze1.explore, args=(u, ))
65+
t2 = threading.Thread(target=aMaze2.explore, args=(v, ))
66+
67+
t1.start()
68+
t2.start()
69+
70+
t1.join()
71+
t2.join()
72+
73+
return MazeGraph.result
74+
75+
if __name__ == '__main__':
76+
input = sys.stdin.read()
77+
data = list(map(int, input.split()))
78+
n, m = data[0:2]
79+
data = data[2:]
80+
edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))
81+
x, y = data[2 * m:]
82+
x, y = x - 1, y - 1
83+
84+
print(reach(n, edges, x, y))

0 commit comments

Comments
 (0)