python 深度优先搜索(DFS)算法在递归和非递归模式下的实现示例,用于图扩展和路径查找。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 深度优先搜索(DFS)算法在递归和非递归模式下的实现示例,用于图扩展和路径查找。相关的知识,希望对你有一定的参考价值。

###GRAPH EXPANSION
##NON RECURSIVE

def dfs(graph, start):
    visited, stack = set(), [start]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.add(vertex)
            stack.extend(graph[vertex] - visited)
    return visited

dfs(graph, 'A') # {'E', 'D', 'F', 'A', 'C', 'B'}

##RECURSIVE

def dfs(graph, start, visited=None):
    if visited is None:
        visited = set()
    visited.add(start)
    for next in graph[start] - visited:
        dfs(graph, next, visited)
    return visited

dfs(graph, 'C') # {'E', 'D', 'F', 'A', 'C', 'B'}

###PATH FINDING
##NON-RECURSIVE

def dfs_paths(graph, start, goal):
    stack = [(start, [start])]
    while stack:
        (vertex, path) = stack.pop()
        for next in graph[vertex] - set(path):
            if next == goal:
                yield path + [next]
            else:
                stack.append((next, path + [next]))

list(dfs_paths(graph, 'A', 'F')) # [['A', 'C', 'F'], ['A', 'B', 'E', 'F']]


##RECURSIVE

def dfs_paths(graph, start, goal, path=None):
    if path is None:
        path = [start]
    if start == goal:
        yield path
    for next in graph[start] - set(path):
        yield from dfs_paths(graph, next, goal, path + [next])

list(dfs_paths(graph, 'C', 'F')) # [['C', 'F'], ['C', 'A', 'B', 'E', 'F']]

以上是关于python 深度优先搜索(DFS)算法在递归和非递归模式下的实现示例,用于图扩展和路径查找。的主要内容,如果未能解决你的问题,请参考以下文章

Python|DFS(深度优先搜索)介绍

Python算法-深度优先搜索&广度优先搜索(DFS&BFS)

层次遍历递归和非递归方法

深度优先(DFS)与广度优先搜索(BFS)递归版与非递归版

binarytree二叉树节点DFS深度优先搜索遍历,递归,python

binarytree二叉树节点DFS深度优先搜索遍历,递归,python