探索迷宫
将海龟放在迷宫中间,如何能找到出口
首先, 我们将整个迷宫的空间(矩形)分为行列整齐的方格,区分出墙壁和通道。
给每个方格具有行列位置,并赋予“墙壁”、 “通道”的属性
迷宫的数据结构
考虑用矩阵方式来实现迷宫数据结构
采用“数据项为字符列表的列表”这种两级列表的方式来保存方格内容,采用不同字符来分别代表“墙壁+”、“通道 ”、“海龟投放点S”从一个文本文件逐行读入迷宫数据
迷宫的数据结构: Maze Class
class Maze:
def __init__(self, mazeFileName):
rowsInMaze = 0
columnsInMaze = 0
self.mazelist = []
mazeFile = open(mazeFileName, 'r')
rowsInMaze = 0
for line in mazeFile:
rowList = []
col = 0
for ch in line[:-1]:
rowList.append(ch)
if ch == 'S':
self.startRow = rowsInMaze
self.startCol = col
col = col + 1
rowsInMaze = rowsInMaze + 1
self.mazelist.append(rowList)
columnsInMaze = len(rowList)
读入数据文件成功后
mazelist如下图示意 mazelist[row][col]==’+’
探索迷宫:算法思路
确定了迷宫数据结构之后, 我们知道,对于海龟来说,其身处某个方格之中
它所能移动的方向,必须是向着通道的方向如果某个方向是墙壁方格,就要换一个方向移动
这样,探索迷宫的递归算法思路如下:
将海龟从原位置向北移动一步,以新位置递归调用探索迷宫寻找出口;
如果上面的步骤找不到出口,那么将海龟从原位置向南移动一步,以新位置递归调用探索迷宫;
如果向南还找不到出口,那么将海龟从原位置向西移动一步,以新位置递归调用探索迷宫;
如果向西还找不到出口,那么将海龟从原位置向东移动一步,以新位置递归调用探索迷宫;
如果上面四个方向都找不到出口,那么这个迷宫没有出口!
思路看起来很完美,但有些细节至关重要
如果我们向某个方向(如北)移动了海龟,那么如果新位置的北正好是一堵墙壁,那么在新位置上的递归调用就会让海龟向南尝试可是新位置的南边一格,正好就是递归调用之前的原位置,这样就陷入了无限递归的死循环之中
所以需要有个机制记录海龟所走过的路径
沿途洒“面包屑”,一旦前进方向发现“面包屑”,就不能再踩上去,而必须换下一个方向尝试对于递归调用来说,就是某方向的方格上发现“面包屑”,就立即从递归调用返回上一级。
递归调用的“基本结束条件”归纳如下:
海龟碰到“墙壁”方格,递归调用结束,返回失败;海龟碰到“面包屑”方格,表示此方格已访问过,递归调用结束,返回失败;海龟碰到“出口”方格,即“位于边缘的通道”方格,递归调用结束,返回成功!海龟在四个方向上探索都失败,递归调用结束,返回失败
探索迷宫:辅助的动画过程
为了让海龟在迷宫图里跑起来, 我们给迷宫数据结构Maze Class添加一些成员和方法
- t:一个作图的海龟,设置其shape为海龟的样子(缺省是一个箭头)
- drawMaze():绘制出迷宫的图形,墙壁用实心方格绘制
- updatePosition(row, col, val):更新海龟的位置,并做标注
- isExit(row, col):判断是否“出口”
代码如下:
import turtle
PART_OF_PATH = 'O'
TRIED = '.'
OBSTACLE = '+'
DEAD_END = '-'
class Maze:
def __init__(self,mazeFileName):
rowsInMaze = 0
columnsInMaze = 0
self.mazelist = []
mazeFile = open(mazeFileName,'r')
rowsInMaze = 0
for line in mazeFile:
rowList = []
col = 0
for ch in line[:-1]:
rowList.append(ch)
if ch == 'S':
self.startRow = rowsInMaze
self.startCol = col
col = col + 1
rowsInMaze = rowsInMaze + 1
self.mazelist.append(rowList)
columnsInMaze = len(rowList)
self.rowsInMaze = rowsInMaze
self.columnsInMaze = columnsInMaze
self.xTranslate = -columnsInMaze/2
self.yTranslate = rowsInMaze/2
self.t = turtle.Turtle()
self.t.shape('turtle')
self.wn = turtle.Screen()
self.wn.setworldcoordinates(-(columnsInMaze-1)/2-.5,-(rowsInMaze-1)/2-.5,(columnsInMaze-1)/2+.5,(rowsInMaze-1)/2+.5)
def drawMaze(self):
self.t.speed(10)
for y in range(self.rowsInMaze):
for x in range(self.columnsInMaze):
if self.mazelist[y][x] == OBSTACLE:
self.drawCenteredBox(x+self.xTranslate,-y+self.yTranslate,'orange')
self.t.color('black')
self.t.fillcolor('blue')
def drawCenteredBox(self,x,y,color):
self.t.up()
self.t.goto(x-.5,y-.5)
self.t.color(color)
self.t.fillcolor(color)
self.t.setheading(90)
self.t.down()
self.t.begin_fill()
for i in range(4):
self.t.forward(1)
self.t.right(90)
self.t.end_fill()
def moveTurtle(self,x,y):
self.t.up()
self.t.setheading(self.t.towards(x+self.xTranslate,-y+self.yTranslate))
self.t.goto(x+self.xTranslate,-y+self.yTranslate)
def dropBreadcrumb(self,color):
self.t.dot(10,color)
def updatePosition(self,row,col,val=None):
if val:
self.mazelist[row][col] = val
self.moveTurtle(col,row)
if val == PART_OF_PATH:
color = 'green'
elif val == OBSTACLE:
color = 'red'
elif val == TRIED:
color = 'black'
elif val == DEAD_END:
color = 'red'
else:
color = None
if color:
self.dropBreadcrumb(color)
def isExit(self,row,col):
return (row == 0 or
row == self.rowsInMaze-1 or
col == 0 or
col == self.columnsInMaze-1 )
def __getitem__(self,idx):
return self.mazelist[idx]
def searchFrom(maze, startRow, startColumn):
# try each of four directions from this point until we find a way out.
# base Case return values:
# 1. We have run into an obstacle, return false
maze.updatePosition(startRow, startColumn)
if maze[startRow][startColumn] == OBSTACLE :
return False
# 2. We have found a square that has already been explored
if maze[startRow][startColumn] == TRIED or maze[startRow][startColumn] == DEAD_END:
return False
# 3. We have found an outside edge not occupied by an obstacle
if maze.isExit(startRow,startColumn):
maze.updatePosition(startRow, startColumn, PART_OF_PATH)
return True
maze.updatePosition(startRow, startColumn, TRIED)
# Otherwise, use logical short circuiting to try each direction
# in turn (if needed)
found = searchFrom(maze, startRow-1, startColumn) or \
searchFrom(maze, startRow+1, startColumn) or \
searchFrom(maze, startRow, startColumn-1) or \
searchFrom(maze, startRow, startColumn+1)
if found:
maze.updatePosition(startRow, startColumn, PART_OF_PATH)
else:
maze.updatePosition(startRow, startColumn, DEAD_END)
return found
myMaze = Maze('maze2.txt')
myMaze.drawMaze()
myMaze.updatePosition(myMaze.startRow,myMaze.startCol)
searchFrom(myMaze, myMaze.startRow, myMaze.startCol)
版权声明:本文不是「本站」原创文章,版权归原作者所有 | 原文地址: