“DFS и BFS в Python” Ответ

DFS и BFS в Python

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

bfs(graph, 'A') # {'B', 'C', 'A', 'F', 'D', 'E'}
Beautiful Bat

DFS и BFS в Python

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']]
Beautiful Bat

DFS и BFS Inn Python

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'}
Beautiful Bat

Ответы похожие на “DFS и BFS в Python”

Вопросы похожие на “DFS и BFS в Python”

Больше похожих ответов на “DFS и BFS в Python” по Python

Смотреть популярные ответы по языку

Смотреть другие языки программирования