#用list来实现栈#定义顺序栈的类classZhan:#定义栈的基本def__init__(self):
self.__zhan =[]#定义显示栈的接口defsee(self):return self.__zhan
#定义入栈操作defpush(self,object):
self.__zhan.append(object)#定义出栈操作defpop(self):iflen(self.__zhan)==0:print("栈为空")returnNoneelse:return self.__zhan.pop()deftop(self):iflen(self.__zhan)==0:print("栈为空")returnNoneelse:return self.__zhan[-1]
migong_zhan = Zhan()
migong_juzhen = \
[[1,1,1,1,1,1,1,1,1],[1,0,1,0,1,1,1,1,1],[1,0,0,0,0,0,1,1,1],[1,0,0,0,1,0,1,1,1],[1,1,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,1,1],[1,1,1,1,0,0,0,1,1],[1,1,1,1,1,1,0,0,1],[1,1,1,1,1,1,1,1,1]]
fuzhu_juzhen = \
[[1,1,1,1,1,1,1,1,1],[1,0,1,0,1,1,1,1,1],[1,0,0,0,0,0,1,1,1],[1,0,0,0,1,0,1,1,1],[1,1,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,1,1],[1,1,1,1,0,0,0,1,0],[1,1,1,1,1,1,0,0,0],[1,1,1,1,1,1,1,1,0]]# 当前坐标
x =1#第几行
y =1#第几列
index =(x,y)#这是起点
final =(7,7)#终点是(8,8)#开始运动:
migong_zhan.push(index)whileTrue:if index==(1,1):if fuzhu_juzhen[x-1][y]==1and fuzhu_juzhen[x+1][y]==1and fuzhu_juzhen[x][y-1]==1and fuzhu_juzhen[x][y+1]==1:print("迷宫走不通")breakif fuzhu_juzhen[x+1][y]==0:
fuzhu_juzhen[x][y]=1
x = x +1
migong_zhan.push((x, y))
index =(x,y)continueelif fuzhu_juzhen[x][y +1]==0:
fuzhu_juzhen[x][y]=1
y = y +1
migong_zhan.push((x, y))
index =(x,y)continueelif index==final:print(migong_zhan.see())print("迷宫已走通")breakelse:if fuzhu_juzhen[x-1][y]==0:
fuzhu_juzhen[x][y]=1
x = x-1
migong_zhan.push((x,y))
index =(x, y)continueelif fuzhu_juzhen[x+1][y]==0:
fuzhu_juzhen[x][y]=1
x = x+1
migong_zhan.push((x,y))
index =(x,y)continueelif fuzhu_juzhen[x][y-1]==0:
fuzhu_juzhen[x][y]=1
y = y-1
migong_zhan.push((x,y))
index =(x,y)continueelif fuzhu_juzhen[x][y+1]==0:
fuzhu_juzhen[x][y]=1
y = y+1
migong_zhan.push((x,y))
index =(x,y)continueelse:
fuzhu_juzhen[x][y]=1
migong_zhan.pop()
index = migong_zhan.top()
x = index[0]
y = index[1]