Last active
October 10, 2018 21:12
-
-
Save AndrewC-B/909237dacdb7305ec256e166287c0b6d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def r_dfs(current: Node, end: Node, all_paths: Set, visited=set(), current_path=[]): | |
visited.add(current) | |
current_path.append(current) | |
if current == end: | |
all_paths.add(tuple(current_path)) # Shallow copy | |
else: | |
for neighbour in current.neighbours() - visited: | |
r_dfs(neighbour, end, all_paths, visited, current_path) | |
current_path.pop() | |
visited.remove(current) | |
def find_paths(start: Node, end: Node): | |
all_paths = set() | |
r_dfs(start, end, all_paths) | |
return all_paths |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def dfs(start: Node): | |
stack = [(None, start)] | |
visited = {start} | |
while len(stack) > 0: | |
parent, current = stack.pop() | |
yield parent, current, visited | |
new_children = current.neighbours() - visited | |
stack += ((current, child) for child in new_children) | |
visited |= new_children | |
def shortest_path(start: Node, end: Node): | |
paths = {None: []} # {destination: [path]} | |
for parent, child, visited in dfs(start): | |
paths[child] = paths[parent] + [child] | |
if child == end: | |
yield paths[child] | |
return None # or raise appropriate exception |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment