基础算法——DFS

以字典存储,递归

# Check for the visisted and unvisited nodes
def dfs(graph, start, visited=None):
    if visited is None:
        visited = set()
    if len(visited) == len(graph):
        return
    else:
        visited.add(start)
        print(start)

    for next in graph[start] - visited:
        dfs(graph, next, visited)

    return visited


graph = {"a": set(["b", "c"]),
         "b": set(["a", "d"]),
         "c": set(["a", "d"]),
         "d": set(["e"]),
         "e": set(["a"])}

print(dfs(graph, 'a'))


以字典存储,非递归

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


graph = {"a": set(["b", "c"]),
         "b": set(["a", "d"]),
         "c": set(["a", "d"]),
         "d": set(["e"]),
         "e": set(["a"])}

print(dfs(graph, 'a'))

你可能感兴趣的:(基础算法)