Chinaunix首页 | 论坛 | 博客
  • 博客访问: 153934
  • 博文数量: 33
  • 博客积分: 2057
  • 博客等级: 大尉
  • 技术积分: 430
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-19 16:37
文章分类
文章存档

2013年(2)

2012年(23)

2011年(8)

分类: Python/Ruby

2012-07-16 10:54:19


点击(此处)折叠或打开

  1. # 12乘15的迷宫,0代表通道单元,1代表障碍单元
  2. # 东南西北,东北,东南,西北,西南共8个方向
  3. # 左上角的0是入口单元,右下角的0是出口单元
  4. m =[ [0,1,0,0,0,1,1,0,0,0,1,1,1,1,1],
  5.      [1,0,0,0,1,1,0,1,1,1,0,0,1,1,1],
  6.      [0,1,1,0,0,0,0,1,1,1,1,0,0,1,1],
  7.      [1,1,0,1,1,1,1,0,1,1,0,1,1,0,0],
  8.      [1,1,0,1,0,0,1,0,1,1,1,1,1,1,1],
  9.      [0,0,1,1,0,1,1,1,0,1,0,0,1,0,1],
  10.      [0,0,1,1,0,1,1,1,0,1,0,0,1,0,1],
  11.      [0,1,1,1,1,0,0,1,1,1,1,1,1,1,1],
  12.      [0,0,1,1,0,1,1,0,1,1,1,1,1,0,1],
  13.      [1,1,0,0,0,1,1,0,1,1,0,0,0,0,0],
  14.      [0,0,1,1,1,1,1,0,0,0,1,1,1,1,0],
  15.      [0,1,0,0,1,1,1,1,1,0,1,1,1,1,0]];
  16. #算法思路:
  17. # 使用一个栈,在python可以用列表当做栈使用
  18. # 一开始,栈中只有入口单元 cell(0,0);其中0,0是单元在迷宫矩阵中所处位置
  19. # 对栈中最上面的单元stack[-1], 寻找相邻的未在栈中出现的通道单元,简称新邻单元
  20. # 如果最上面单元即是出口单元,则打印出栈中内容即为迷宫的解答路径,跳出循环
  21. # 否则如果最上面的单元的8个方向还有未试探的,试探这个方向的新邻单元;有新邻单元就压入栈中
  22. # 否则,从栈中弹出该单元
  23. class cell:
  24.     def __init__(self,x,y):
  25.         self.x,self.y=x,y
  26.         if self.x>=0 and self.x<len(m) and self.y>=0 and self.y<len(m[-1]): self.value=m[self.x][self.y]
  27.         else: self.value=1
  28.         self.direction=0
  29.     def newnextcell(self):
  30.         ds=((0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1),(-1,0),(-1,1))
  31.         i,j = ds[self.direction]
  32.         self.direction += 1
  33.         return cell(self.x+i,self.y+j)
  34. stack=[cell(0,0)]

  35. while(stack):
  36.     curcell=stack[-1]
  37.     if (curcell.x,curcell.y)==(len(m)-1,len(m[-1])-1): print([(c.x,c.y) for c in stack]);break
  38.     elif curcell.direction < 8:
  39.         nn=curcell.newnextcell()
  40.         if nn.value==0 and (nn.x,nn.y) not in [(c.x,c.y) for c in stack]: stack.append(nn)
  41.     else: stack.pop()

阅读(3178) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~