forked from seungjae02/PathfindingVisualizer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dfs_class.py
89 lines (68 loc) · 2.77 KB
/
dfs_class.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
80
81
82
83
from settings import *
class DepthFirst():
def __init__(self, app, start_node_x, start_node_y, end_node_x, end_node_y, wall_pos):
self.app = app
self.start_node_x = start_node_x
self.start_node_y = start_node_y
self.end_node_x = end_node_x
self.end_node_y = end_node_y
self.wall_pos = wall_pos
self.visited = [(self.start_node_x, self.start_node_y)]
self.route = None
self.route_found = False
def draw_all_paths(self, i, j):
##### Draw each node the computer is visiting as it is searching SIMULTNEOUSLY
pygame.draw.rect(self.app.screen, TAN, (i * 24 + 240, j * 24, 24, 24), 0)
##### Redraw start/end nodes on top of all routes
pygame.draw.rect(self.app.screen, TOMATO,
(240 + self.start_node_x * 24, self.start_node_y * 24, 24, 24), 0)
pygame.draw.rect(self.app.screen, ROYALBLUE,
(240 + self.end_node_x * 24, self.end_node_y * 24, 24, 24), 0)
# Redraw grid (for aesthetic purposes lol)
for x in range(52):
pygame.draw.line(self.app.screen, ALICE, (GS_X + x * 24, GS_Y),
(GS_X + x * 24, GE_Y))
for y in range(30):
pygame.draw.line(self.app.screen, ALICE, (GS_X, GS_Y + y * 24),
(GE_X, GS_Y + y * 24))
pygame.display.update()
def checkValid(self, move):
if move not in self.wall_pos and move not in self.visited:
self.visited.append(move)
return True
return False
def findEnd(self, first_in):
if first_in == (self.end_node_x, self.end_node_y):
return True
return False
def dfs_execute(self):
stack = []
first_in = (self.start_node_x, self.start_node_y)
stack.append(first_in)
moves_stack = []
moves_first_in = ''
moves_stack.append(moves_first_in)
while len(stack) > 0:
last_out = stack.pop()
moves_last_out = moves_stack.pop()
for m in ['L', 'R', 'U', 'D']:
i, j = last_out
if m == 'L':
i -= 1
elif m == 'R':
i += 1
elif m == 'U':
j -= 1
elif m == 'D':
j += 1
move_update = moves_last_out + m
if self.findEnd((i, j)):
self.route = move_update
self.route_found = True
break
if self.checkValid((i, j)):
stack.append((i, j))
moves_stack.append(move_update)
self.draw_all_paths(i, j)
if self.route_found:
break