Depth-First Graph Traversal

Run Settings
LanguagePython
Language Version
Run Command
''' Prints the shortest path to the target node. ''' graph = { 0: [1, 2, 3], 1: [4, 5], 2: [6, 7] } visited = [] def dfs(g, start, target, path): visited.append(start) if start == target: return path + ' ' + str(start) else: for node in g.get(start, []): if node not in visited: p = dfs(g, node, target, path + ' ' + str(start)) if p: return p print(dfs(graph, 0, 5, "")) print(visited)
Editor Settings
Theme
Key bindings
Full width
Lines