内联解释def solve(self, x=None, y=None):
# initializes x, y as start location
# occurs during first call of 'solve', i.e. zeroth recursion
if x==None:
x, y = self.start_x,self.start_y
# equivalent to, if the current (x, y) tile is walk-able
# implicitly ignores visited tiles
if self.maze[y][x] in (PATH,START):
# mark tile (x, y) as visited
self.maze[y][x] = VISITED
# if one of the adjacent tiles from (x, y) leads to a solution
# this is where the recursion occurs, i.e. 'solve' is called using the adjacent tiles
# this will be recursively called until one of the calls return True upon finding the exit
# when one of the calls encounter an exit, then this will create a chain reaction where each call returns True to its caller until the first call returns true
if self.solve(x+1,y) or self.solve(x-1,y) or self.solve(x,y+1) or self.solve(x,y-1):
# mark (x, y) as part of the solution
self.maze[y][x]=SOLUTION
# tells that a solution has been found, value used by caller
return True
# if the (x, y) tile is the exit then a solution has been found
elif self.maze[y][x] == EXIT:
return True
# if non of the if statements return, then by default no solution has been found where tile (x, y) is in the solution path.
return False
迷宫传说可漫游的磁贴
S开始平铺
E退出磁贴
.访问的磁贴
o是解决方案路径的一部分的平铺
所有其他瓷砖都是不可行走的瓷砖
迷宫前solve()
^{pr2}$
迷宫后solve()+-+-+-+-+-+-+-+-+-+-+
| |.........|...|...|
oo+-+-+-+-+.+.+-+.+.+
|ooooooo..|.|.....|.|
+-+-+-+o+-+.+-+-+-+.+
|ooo..|o|...|.......|
+o+o+.+o+.+-+.+-+-+-+
|o|o|.|o|.......|...|
+o+o+-+o+-+-+.+.+.+.+
|o|ooo|o|ooo|.|...|.|
+o+-+o+o+o+o+.+-+-+-+
|o|ooo|ooo|o|.......|
+o+o+-+-+-+o+.+-+-+.+
|o|ooooooooo|.|.....|
+o+-+-+ +-+-+.+-+-+-+
|o|ooo| |...| |
+o+o+o+-+-+-+-+.+ +-+
|o|o|o| |ooo....| |
+o+o+o+ +o+o+-+-+-+ +
|ooo|ooooo|oooooooooE
+-+-+-+-+-+-+-+-+-+-+