zoukankan      html  css  js  c++  java
  • 回溯法-迷宫问题

    回溯法(探索与回溯法)是一种选优搜索法,又称为试探法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。

    我们用回溯法来写迷宫问题,如下:

    maze = [[0, 0, 1, 1, 1, 1, 1, 1],
    [1, 0, 1, 0, 1, 1, 0, 1],
    [1, 0, 0, 1, 1, 1, 0, 1],
    [1, 0, 1, 0, 0, 0, 0, 1],
    [1, 0, 0, 0, 1, 0, 1, 1],
    [1, 1, 1, 0, 1, 0, 1, 1],
    [1, 0, 0, 0, 1, 0, 0, 1],
    [1, 1, 1, 1, 1, 1, 0, 1]]

    stack = []
    dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    def mark(m, p):
    m[p[0]][p[1]] = 2
    def judge(m, p):
    return m[p[0]][p[1]] == 0
    def maze_solver(m, s, e):
    if s == e:
    print(s)
    return
    mark(m, s)
    stack.append(s)
    while len(stack):
    pos = stack[-1]
    stack.pop()
    for i in range(4):
    nextp = (pos[0] + dirs[i][0], pos[1] + dirs[i][1])
    if nextp == e:
    print("路径:", stack)
    return
    if judge(m, nextp):
    stack.append(pos)
    mark(m, nextp)
    stack.append(nextp)
    break
    print("找不到路径")
    for i in range(8):
    for j in range(8):
    print(maze[i][j], end='')
    print()
    maze_solver(maze, s=(0, 0), e=(7, 7))
  • 相关阅读:
    jq的stop
    mouseover,mouseout与mouseenter,mouseleave
    jq的load
    KeyUp 和KeyDown 、KeyPress之间的区别
    jq的error
    $(function() {....}) ,(function($){...})(jQuery)
    delegate事件委托
    将项目提交到git
    linux下安装jenkins
    手写简单的linkedlist
  • 原文地址:https://www.cnblogs.com/whitehawk/p/10964846.html
Copyright © 2011-2022 走看看