-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbidirectional_bfs.py
79 lines (60 loc) · 1.93 KB
/
bidirectional_bfs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import pygame
from Algorithms.bfs import color_bfs_path
def bidirectional_bfs(draw, grid, start, end):
queue1 = []
queue2 = []
t1 = (start.row, start.col)
t2 = (end.row, end.col)
queue1.append([t1])
queue2.append([t2])
while queue1 and queue2:
path1 = []
path2 = []
path1 = queue1.pop(0)
path2 = queue2.pop(0)
node1 = path1[-1]
node2 = path2[-1]
grid[node1[0]][node1[1]].isVisited[0] = 1
grid[node1[0]][node1[1]].make_closed()
grid[node2[0]][node2[1]].isVisited[1] = 1
grid[node2[0]][node2[1]].make_closed()
aux1 = grid[node1[0]][node1[1]].isVisited[1]
aux2 = grid[node2[0]][node2[1]].isVisited[0]
if aux1 == 1 or aux2 == 1 or (node1[0] == node2[0] and node1[1] == node2[1]):
#x.make_barrier()
if aux1 == 1:
while queue2:
path2 = queue2.pop(0)
node = path2[-1]
if node[0] == node1[0] and node[1] == node1[1]:
path2.reverse()
path = path1 + path2
color_bfs_path(path, grid, draw)
return
if aux2 == 1:
while queue1:
path1 = queue1.pop(0)
node = path1[-1]
if node[0] == node2[0] and node[1] == node2[1]:
path1.reverse()
path = path2 + path1
color_bfs_path(path, grid, draw)
return
for adjacent in grid[node1[0]][node1[1]].neighbors:
if (grid[adjacent.row][adjacent.col]).isVisited[0] == 0:
adjacent.make_open()
new_path = list(path1)
t = (adjacent.row, adjacent.col)
new_path.append(t)
queue1.append(new_path)
grid[adjacent.row][adjacent.col].isVisited[0] = 1
draw()
for adjacent in grid[node2[0]][node2[1]].neighbors:
if (grid[adjacent.row][adjacent.col]).isVisited[1] == 0:
adjacent.make_open()
new_path = list(path2)
t = (adjacent.row, adjacent.col)
new_path.append(t)
queue2.append(new_path)
grid[adjacent.row][adjacent.col].isVisited[1] = 1
draw()