-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDFS.py
115 lines (78 loc) · 2.66 KB
/
DFS.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#* **** DEPTH-FIRST SEARCH ****
# by Shrey Biswas
#* IMPORTS
import random
import pygame
from sys import exit
from time import sleep
from Maze_Generator import *
from screen_details import *
#* PARAMETERS
maze = False
diagonal = False
if not maze: # maze cannot be diagonal
diagonal = True
# pylint: disable=no-member
grid = build_blank_grid()
grid = add_blocks(grid)
if maze:
grid = generate_maze(grid,animate=False)
for row in grid: # reset
for cell in row:
cell.visited = False
def Depth_First_Search(grid):
for row in grid: # find start and target cells
for cell in row:
if cell.cell_type == 'Start':
start_cell = cell
elif cell.cell_type == 'Target':
target_cell = cell
frontier = []
current_cell = start_cell
#* Search
while current_cell != target_cell:
#sleep(1)
current_cell.visited = True
if not maze: #* maze cells already have 'children' with set values, non-maze is empty
current_cell.find_neighbours(grid,diagonal)
random.shuffle(current_cell.children)
#* filter out cells already in frontier, blocked, or visited
frontier = list(filter(lambda cell: cell not in current_cell.children and cell.cell_type != 'Block' and not cell.visited,frontier))
frontier += current_cell.children
try:
next_cell = frontier.pop(-1)
except:
print('No Solution')
pygame.quit()
exit()
while current_cell not in next_cell.potential_parents: #* backtracks current_cell towards next_cell
current_cell.draw(RED)
current_cell.parent.draw(MAGENTA)
sleep(cellWidth/1000)
pygame.display.update()
current_cell = current_cell.parent
next_cell.draw(PINK)
pygame.display.update()
sleep(cellWidth/1500)
current_cell.draw(RED)
next_cell.parent = current_cell
current_cell = next_cell
route = []
#* Trace path back
while current_cell != start_cell:
route.append(current_cell)
next_cell = current_cell.potential_parents[0] # first parent is the quickest route (earliest to be highlighted)
next_cell.draw(TURQ)
pygame.display.update()
sleep(cellWidth/4000)
current_cell.connect(next_cell,GREEN,diagonal)
current_cell = next_cell
return route
################################################################
#* main
Depth_First_Search(grid)
while True:
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()