Path: blob/master/languages/python/algorithm_traversal.py
1240 views
from collections import deque123def bfs(g, start):4queue, enqueued = deque([(None, start)]), set([start])5while queue:6parent, n = queue.popleft()7yield parent, n8new = set(g[n]) - enqueued9enqueued |= new10queue.extend([(n, child) for child in new])1112def dfs(g, start):13stack, enqueued = [(None, start)], set([start])14while stack:15parent, n = stack.pop()16yield parent, n17new = set(g[n]) - enqueued18enqueued |= new19stack.extend([(n, child) for child in new])2021def shortest_path(g, start, end):22parents = {}23for parent, child in bfs(g, start):24parents[child] = parent25if child == end:26revpath = [end]27while True:28parent = parents[child]29revpath.append(parent)30if parent == start:31break32child = parent33return list(reversed(revpath))34return None # or raise appropriate exception3536if __name__ == '__main__':37# a sample graph38graph = {'A': ['B', 'C','E'],39'B': ['A','C', 'D'],40'C': ['D'],41'D': ['C'],42'E': ['F', 'D'],43'F': ['C']}4445for node in bfs(graph,'A'):46print(node)474849