python dfs和bfs

def bfs(graph, start):
    visited = []
    queue = [start]
 
    while queue:
        node = queue.pop(0)
        if node not in visited:
            visited.append(node)
            neighbours = graph[node]
            for neighbour in neighbours:
                queue.append(neighbour)
    return visited

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

graph={   'Amin'  : {'Wasim', 'Nick', 'Mike'},
         'Wasim' : {'Imran', 'Amin'}, 
         'Imran' : {'Wasim','Faras'}, 
         'Faras' : {'Imran'},
         'Mike':{'Amin'}, 
         'Nick':{'Amin'}}

bfs(graph,'Amin')
dfs(graph,'Amin')

上一篇:151. Reverse Words in a String翻转一句话中的单词


下一篇:论文解读《The Emerging Field of Signal Processing on Graphs》