zoukankan      html  css  js  c++  java
  • 走迷宫问题

    输入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     遍历周围4个点:
    25         如果周围节点不是-1 说明 不是障碍 在此基础上:
    26                 里面是0 说明没遍历过 我们把它修改成当前所在位置步数加1
    27                 里面比当前的next_step大 说明不是最优方案 就修改它
    28                 里面比当前next_step说明当前不是最优方案,不修改
    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])
  • 相关阅读:
    教你怎么买虚拟空间(转)
    一个超棒的jQuery通知栏插件 jBar
    GBin1专题之Web热点秀#12
    19套最新的免费图标字体集
    帮助你操作数字和处理数字格式的javascript类库 Numeral.js
    分享两个超棒的帮助你生成占位图片(placeholder image)的在线工具
    分享40个超棒的CSS3按钮教程
    一款非常棒的CSS 3D下拉式菜单实现Makisu
    47款超酷超实用的CSS3技巧教程
    不容错过的精选免费jQuery UI主题大荟萃
  • 原文地址:https://www.cnblogs.com/Lin-Yi/p/7355428.html
Copyright © 2011-2022 走看看