图及算法----遍历算法(迭代实现)

1. 图的遍历

2.

3.

class Graph: 
    def __init__(self): 
        self.graph: Dict[str, List[str]] = defaultdict(list)
    
    def addEdge(self, u, v): 
        self.graph[u].append(v)
        
def dfs_traverse(graph, start):
    visited, stack = set(), [start]
    while stack:
        node = stack.pop()
        if node not in visited:
            visited.add(node)
            for nextNode in graph[node]:
                if nextNode not in visited:
                    stack.append(nextNode)
    return visited


def bfs_traverse(graph, start):
    visited, queue = set(), [start]
    while queue:
        node = queue.pop(0)
        if node not in visited:
            visited.add(node)
            for nextNode in graph[node]:
                if nextNode not in visited:
                    queue.append(nextNode)
    return visited

# 想象有个Actor在结构上行走,它必须维护它的状态的变更,这是搜索的本质

def BFS(graph, s): 
    visited = set()
    queue = [] 
    queue.append(s) 
    while queue: 
        s = queue.pop(0) 
        print(s, end=" ") 
        for i in graph[s]: 
            if i not in visited: 
                visited.add(i)
                queue.append(i) 
    return visited

def BFS2(graph, s): 
    visited = set()
    queue = [] 
    while True:
        print(s, end=" ") 
        for i in graph[s]: 
            if i not in visited: 
                visited.add(i)
                queue.append(i)
        if queue:
            s = queue.pop(0) 
        else:
            break
        
        print(queue)
    return visited

猜你喜欢

转载自www.cnblogs.com/wdmx/p/10076336.html