hezq0629

导航

 

DFS是一种用于遍历或搜索树、图等结构的经典算法。其核心思想是沿一条路径尽可能深入,遇到无法继续的节点时再回溯到上一个分叉点,继续探索其他路径,直到遍历完整个结构或找到目标为止。
img

问题实践

以一个4*4的迷宫为例,其中0表示可走,1表示障碍物,起点为(0,0),终点为(3,3)。迷宫可表示为:

0 1 0 0
0 0 0 1
1 0 1 1
0 0 0 0

运行结果如下:

find the path  
(0, 0) -> (1, 0) -> (1, 1) -> (2, 1) -> (3, 1) -> (3, 2) -> (3, 3)
Path length: 6 steps

代码编写(基于堆栈的方法):

class Node:                       #定义节点状态
    def __init__(self,x,y,parent=None,depth=0):
        self.x = x
        self.y = y
        self.parent = parent       #父节点
        self.depth = depth         #当前路径的深度

def DFS(node_start,node_end):
    
    visited = [[0 for _ in range(m)] for _ in range(n)]
    path = []
    path.append(node_start)
    visited[node_start.x][node_start.y] = True

    while path:                     
        node_current = path[-1]    #path[-1]代表栈顶节点
        if node_current.x == node_end.x and node_current.y == node_end.y: #判断是否到达终点,是则退出循环
            print("find the path")
            for node in path:
                print(f"({node.x}, {node.y})", end="")
                node_current = node_current.parent
                if node_current:
                    print(" -> ", end="")
            print(end='\n')
            print(f"Path length: {len(path) - 1} steps")
            return True
        
        has_visited = False        #判断当前节点是否访问过

        for i in range(4):         #判断四个方向是否可以走,可以则入栈
            next_x = node_current.x + directions[i][0]
            next_y = node_current.y + directions[i][1]
            if next_x >= 0 and next_x < n and next_y >= 0 and next_y < m:
                if maze[next_x][next_y] == 0 and visited[next_x][next_y] == 0:  #判断四周是否为障碍物且是否访问过
                    next_node=Node(next_x,next_y,node_current,node_current.depth+1)
                    visited[next_x][next_y] = True
                    path.append(next_node)
                    has_visited = True
                    break
        if not has_visited:      #如果四个方向均无法走,则回溯到上一个节点
            path.pop()
        
    print("can't find the path")

主函数

if __name__ == "__main__":
    m = 4
    n = 4
    maze = [[0 for _ in range(m)] for _ in range(n)]
    maze[0] = [0,1,0,0]
    maze[1] = [0,0,0,1]
    maze[2] = [1,0,1,1]
    maze[3] = [0,0,0,0]
    directions = [[0,-1],[-1,0],[0,1],[1,0]] #左,上,右,下
    # 设置起点和终点(坐标从0开始)
    start = Node(0, 0)
    end = Node(3, 3)
    # 执行DFS搜索
    DFS(start, end)

在学习过程中,发现还有基于递归方式的DFS算法,如下
img

posted on 2025-10-19 20:48  hzq123321  阅读(2)  评论(0)    收藏  举报