首页 > 其他 > 详细

走迷宫问题

时间:2017-08-13 23:58:43      阅读:315      评论:0      收藏:0      [点我收藏+]
输入n * m 的二维数组 表示一个迷宫
数字0表示障碍 1表示能通行
移动到相邻单元格用1步


思路:
深度优先遍历,到达每一个点,记录从起点到达每一个点的最短步数

初始化案例:
1 1 0 1 1
1 0 1 1 1
1 0 1 0 0
1 0 1 1 1
1 1 1 0 1
1 1 1 1 1

1 把图周围加上一圈-1 , 在深度优先遍历的时候防止出界
2 把所有障碍改成-1,把能走的地方改成0
3 每次遍历经历某个点的时候,如果当前节点值是0 把花费的步数存到节点里
如果当前节点值是-1 代表是障碍 不遍历它
如果走到当前节点花费的步数比里面存的小,就修改它

修改后的图:
-1 -1 -1 -1 -1 -1 -1

-1 0 0 -1 0 0 -1
-1 0 -1 0 0 0 -1
-1 0 -1 0 -1 -1 -1
-1 0 -1 0 0 0 -1
-1 0 0 0 -1 0 -1
-1 0 0 0 0 0 -1

-1 -1 -1 -1 -1 -1 -1

外周的-1 是遍历的时候防止出界的


默认从左上角的点是入口 右上角的点是出口
 1 def init():
 2     global graph
 3     graph.append([-1,   -1, -1, -1, -1, -1,   -1])
 4 
 5     graph.append([-1,    0,  0, -1,  0,  0,   -1])
 6     graph.append([-1,    0, -1,  0,  0,  0,   -1])
 7     graph.append([-1,    0, -1,  0, -1, -1,   -1])
 8     graph.append([-1,    0, -1,  0,  0,  0,   -1])
 9     graph.append([-1,    0,  0,  0, -1,  0,   -1])
10     graph.append([-1,    0,  0,  0,  0,  0,   -1])
11 
12     graph.append([-1,   -1, -1, -1, -1, -1,   -1])
13 
14 #深度优先遍历
15 def deepFirstSearch( steps , x, y ):
16 
17     global graph
18     current_step = steps + 1
19     print(x, y, current_step )
20 
21     graph[x][y] = current_step
22     next_step = current_step + 1
23     ‘‘‘
24     遍历周围8个节点:
25         1如果周围节点不是-1 说明 不是障碍 在此基础上:
26                 里面是0 说明没遍历过
27                 里面比当前的next_step大 说明不是最优方案
28                 满足以上 就修改它
29     ‘‘‘
30 
31     if not(x-1== 1 and y==1) and graph[x-1][y] != -1  and  ( graph[x-1][y]>next_step or graph[x-1][y] ==0 ) : #
32         deepFirstSearch(current_step, x-1 , y )
33     if not(x == 1 and y-1==1) and graph[x][y-1] != -1 and  ( graph[x][y-1]>next_step or graph[x][y-1] ==0 ) : #
34         deepFirstSearch(current_step, x , y-1 )
35     if not(x == 1 and y+1==1) and graph[x][y+1] != -1 and  ( graph[x][y+1]>next_step or graph[x][y+1]==0 ) : #
36         deepFirstSearch(current_step, x , y+1 )
37     if not(x+1== 1 and y==1) and graph[x+1][y] != -1 and  ( graph[x+1][y]>next_step or graph[x+1][y]==0 )  : #
38         deepFirstSearch(current_step, x+1 , y )
39 
40 
41 
42 
43 if __name__ == "__main__":
44     graph = []
45     init()
46 
47     deepFirstSearch(-1,1,1)
48     print(graph[1][5])

 

走迷宫问题

原文:http://www.cnblogs.com/Lin-Yi/p/7355428.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!