To find shortest path • We need to keep track of the best path found so far • When we find a new path, keep going only if path s:ll shorter than best seen so far Be<er depth first search 0 1 2 0 1 0 3 2 2 3 4 4 5 4 1 0 Be<er depth first search 0 1 2 0 1 0 01 02 3 2 2 3 4 4 5 4 1 0 Simple depth first search 0 1 2 XX 0 1 0 01 02 012 02 3 2 2 3 4 4 5 4 1 0 Simple depth first search 0 1 2 XX 0 1 3 2 2 0 01 02 012 02 0123 0124 02 3 4 4 5 4 1 0 Simple depth first search 0 1 2 XX 0 1 3 2 2 3 4 4 5 4 1 0 01234 01235 0124 02 4 5 01 02 012 02 0123 0124 02 0 Simple depth first search 0 1 2 XX 0 1 3 2 2 3 4 4 5 4 1 0 01234 01235 0124 02 4 01 02 5 01235 0124 02 012 02 0123 0124 02 0 Simple depth first search 0 1 2 XX 0 1 3 2 2 3 4 4 5 4 1 0 01234 01235 0124 02 4 01 02 5 01235 0124 02 012 02 0123 0124 02 0 Simple depth first search 0 1 2 XX 0 1 3 2 2 3 4 XX 4 5 4 1 0 01234 01235 0124 02 4 01 02 5 01235 0124 02 012 02 02 0123 0124 02 0 Simple depth first search 0 1 2 XX 0 1 3 2 2 3 4 XX 4 5 4 1 0 01234 01235 0124 02 4 01 02 5 01235 0124 02 012 02 02 0123 0124 02 023 024 0 Simple depth first search 0 1 2 XX 0 1 3 2 2 3 4 XX 4 5 4 1 0 0 01234 01235 0124 02 0234 0235 0231 024 4 01 02 5 01235 0124 02 012 02 02 0123 0124 02 023 024 Simple depth first search 0 1 2 XX 0 1 3 2 2 3 4 4 XX XX 5 4 1 0 0 01234 01235 0124 02 0234 0235 0231 024 4 01 02 5 01235 0124 02 012 02 02 0123 0124 02 023 024 Simple depth first search 0 1 2 XX 0 1 3 2 2 3 4 4 XX XX 5 4 1 0 0 01234 01235 0124 02 0234 0235 0231 024 4 01 02 5 01235 0124 02 0235 0231 024 012 02 02 0123 0124 02 023 024 Simple depth first search 0 1 2 XX 0 3 2 4 XX 1 2 3 4 4 XX XX 5 1 XX 0 0 01234 01235 0124 02 0234 0235 0231 024 4 01 02 5 01235 0124 02 0235 0231 024 012 02 02 024 0123 0124 02 023 024 Simple depth first search 0 1 2 XX 0 3 2 4 XX 1 2 3 4 4 XX XX 5 1 XX 0 0 01234 01235 0124 02 0234 0235 0231 024 4 01 02 5 01235 0124 02 0235 0231 024 012 02 02 024 0123 0124 02 023 024 A shortest path DFS algorithm def DFS(graph, start, end, path = [],shortest = None): # Assumes graph is a Digraph # Assumes start and end are nodes in graph path = path + [start] print 'Current dfs path:', printPath(path) if start == end: return path for node in graph.childrenOf(start): if node not in path: # Avoid cycles if shortest == None or len(path) < len(shortest): newPath = DFS(graph, node, end, path, shortest) if newPath != None: shortest = newPath return shortest
© Copyright 2026 Paperzz