def dfs(graph: Digraph, start, end, path, shortest, to_print=False): path = path + [start] if to_print: print(f'Current dfs path: {print_path(path)}') if start == end: return path for node in graph.get_children(start): # no cycles if node not in path: if shortest == None or len(path) < len(shortest): new_path = dfs(graph, node, end, path, shortest, to_print) if new_path != None: shortest = new_path elif to_print: print(f'{node} already visited') return shortest
def bfs(graph: Digraph, start, end, to_print=False): init_path = [start] # queue is a list of paths path_queue = [init_path] while len(path_queue) != 0: tmp_path = path_queue.pop(0) if to_print: print(f'current bfs path: {print_path(tmp_path)}') last_node = tmp_path[-1] if last_node == end: return tmp_path for next_node in graph.get_children(last_node): if next_node not in tmp_path: new_path = tmp_path + [next_node] path_queue.append(new_path) return None