-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathSHORTEST PATH FINDER(BFS).py
More file actions
94 lines (75 loc) · 2.62 KB
/
SHORTEST PATH FINDER(BFS).py
File metadata and controls
94 lines (75 loc) · 2.62 KB
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
import curses
from curses import wrapper
import queue
import time
maze = [
["#", "#", "#", "#", "O", "#", "#", "#", "#"],
["#", " ", " ", " ", " ", " ", " ", " ", "#"],
["#", " ", "#", "#", " ", "#", "#", " ", "#"],
["#", " ", "#", " ", " ", " ", "#", " ", "#"],
["#", " ", "#", " ", "#", " ", "#", " ", "#"],
["#", " ", "#", " ", "#", " ", "#", " ", "#"],
["#", " ", "#", " ", "#", " ", "#", "#", "#"],
["#", " ", " ", " ", " ", " ", " ", " ", "#"],
["#", "#", "#", "#", "#", "#", "#", "X", "#"]
]
def print_maze(maze,stdscr,path=[]):
BLUE=curses.color_pair(1)
RED=curses.color_pair(2)
#enumerate lets you loop through index and elements also
for i,row in enumerate(maze): #i is the row(index) in maze row is the list on that i
for j,value in enumerate(row): #j is the col in the row and value means "#" or "x" or " "
if (i,j) in path:
stdscr.addstr(i,j*2 ,"X",RED)
else:
stdscr.addstr(i,j*2 ,value,BLUE)
def find_start(maze,start):
for i,row in enumerate(maze):
for j,value in enumerate(row):
if value==start:
return i,j
return None
def bfs(maze,stdscr):
start="O"
end="X"
start_pos=find_start(maze,start)
q=queue.Queue()
q.put((start_pos,[start_pos]))
visited=set({})
while not q.empty():
current_pos,path=q.get()
row,col=current_pos
stdscr.clear() #clear the entire screen
print_maze(maze,stdscr,path) #top left corner
time.sleep(0.2)
stdscr.refresh()#refresh the screen
if maze[row][col]==end:
return path
neighbors=find_neighbors(maze,row,col)
for neighbor in neighbors:
if neighbor in visited:
continue
r,c=neighbor
if maze[r][c]=="#":
continue
new_path=path+[neighbor]
q.put((neighbor,new_path))
visited.add(neighbor)
def find_neighbors(maze,row,col):
neighbors=[]
if row>0: #up
neighbors.append((row-1,col))
if row+1<len(maze):#down
neighbors.append((row+1,col))
if col>0:#left
neighbors.append((row,col-1))
if col+1<len(maze[0]):#right
neighbors.append((row,col+1))
return neighbors
def main(stdscr):
curses.init_pair(1,curses.COLOR_BLUE,curses.COLOR_BLACK)#initialize the color
curses.init_pair(2,curses.COLOR_RED,curses.COLOR_BLACK)
#blue_and_black=curses.color_pair(1) #using the color pair
bfs(maze,stdscr)
stdscr.getch() #get char similar to input statement
wrapper(main)