33from config import config
44from collections import deque
55import time
6+ import pygame
7+
8+
9+ def is_valid (mat , visited , row , col ):
10+ M , N = mat .shape
11+ return (row >= 0 ) and (row < M ) and (col >= 0 ) and (col < N ) \
12+ and mat [row ][col ] == 0 and not visited [row ][col ]
613
714
815def dfs (win , startEnd , walls ):
16+ clock = pygame .time .Clock ()
917 start , end = startEnd
1018 start_x , start_y = start
1119 end_x , end_y = end
1220 mat = np .zeros ([config ['board' ]['w' ], config ['board' ]['h' ]])
1321 for i in walls :
1422 mat [i ] = 1
1523 M , N = mat .shape
16-
1724
25+ # explore 4 neighbors
26+ row = [- 1 , 0 , 0 , 1 ]
27+ col = [0 , - 1 , 1 , 0 ]
28+ move = ['L' , 'U' , 'D' , 'R' ]
29+ q = deque ()
30+
31+ visited = [[False for _ in range (N )] for __ in range (M )]
32+ visited [start_x ][start_y ] = True
33+ add = ""
34+ q .append ((start_x , start_y , 0 , add ))
35+ min_dist = sys .maxsize
36+
37+ while q :
38+ (start_x , start_y , dist , add ) = q [- 1 ]
39+ if start_x == end_x and start_y == end_y :
40+ min_dist = dist
41+ break
42+ found = False
43+ for k in range (4 ):
44+ if is_valid (mat , visited , start_x + row [k ], start_y + col [k ]):
45+ visited [start_x + row [k ]][start_y + col [k ]] = True
46+
47+ win .write ('*' , start_x + row [k ], start_y + col [k ], fgcolor = 'green' )
48+ pygame .time .wait (3 )
49+ q .append ((start_x + row [k ], start_y + col [k ], dist + 1 , add + move [k ]))
50+ found = True
51+ break
52+ if not found :
53+ q .pop ()
54+ win .write ('@' , end_x , end_y )
55+
56+ if min_dist != sys .maxsize :
57+ # find path
58+ start_x , start_y = startEnd [0 ]
59+ for i in range (len (add )):
60+ for event in pygame .event .get ():
61+ # Quit if the user closes the window.
62+ if event .type == pygame .QUIT :
63+ return
64+ index = move .index (add [i ])
65+ start_x , start_y = start_x + row [index ], start_y + col [index ]
66+ win .write ('+' , start_x , start_y , fgcolor = 'red' )
67+ pygame .time .wait (5 )
68+ win .write ('@' , end_x , end_y )
69+ win .write (f"The path from source to destination has length { min_dist } " , 1 , 1 )
70+ else :
71+ win .write ("Destination can't be reached from a given source" , 1 , 1 )
0 commit comments