国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python解決走迷宮問題算法示例

2020-02-15 22:34:32
字體:
來源:轉載
供稿:網友

本文實例講述了Python解決走迷宮問題算法。分享給大家供大家參考,具體如下:

問題:

輸入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 是遍歷的時候防止出界的

默認從左上角的點是入口 右上角的點是出口

Python代碼:

# -*- coding:utf-8 -*-def init():  global graph  graph.append([-1,  -1, -1, -1, -1, -1,  -1])  graph.append([-1,  0, 0, -1, 0, 0,  -1])  graph.append([-1,  0, -1, 0, 0, 0,  -1])  graph.append([-1,  0, -1, 0, -1, -1,  -1])  graph.append([-1,  0, -1, 0, 0, 0,  -1])  graph.append([-1,  0, 0, 0, -1, 0,  -1])  graph.append([-1,  0, 0, 0, 0, 0,  -1])  graph.append([-1,  -1, -1, -1, -1, -1,  -1])#深度優先遍歷def deepFirstSearch( steps , x, y ):  global graph  current_step = steps + 1  print(x, y, current_step )  graph[x][y] = current_step  next_step = current_step + 1  '''  遍歷周圍4個點:    如果周圍節點不是-1 說明 不是障礙 在此基礎上:        里面是0 說明沒遍歷過 我們把它修改成當前所在位置步數加1        里面比當前的next_step大 說明不是最優方案 就修改它        里面比當前next_step說明當前不是最優方案,不修改  '''  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 ) : #左    deepFirstSearch(current_step, x-1 , y )  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 ) : #上    deepFirstSearch(current_step, x , y-1 )  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 ) : #下    deepFirstSearch(current_step, x , y+1 )  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 ) : #右    deepFirstSearch(current_step, x+1 , y )if __name__ == "__main__":  graph = []  init()  deepFirstSearch(-1,1,1)  print(graph[1][5])            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 阿拉善盟| 文登市| 苏尼特左旗| 江华| 崇左市| 安西县| 平武县| 罗定市| 夏河县| 迁安市| 博湖县| 璧山县| 扬中市| 道真| 武义县| 衡山县| 多伦县| 同江市| 方城县| 中江县| 渝中区| 灌云县| 喀什市| 隆林| 平武县| 应用必备| 宁河县| 宝兴县| 平凉市| 乌拉特前旗| 凤山县| 合江县| 杭锦后旗| 平南县| 定州市| 通榆县| 烟台市| 壶关县| 襄汾县| 礼泉县| 武平县|