Skip to content

Instantly share code, notes, and snippets.

@svalleru
Created June 15, 2016 18:30
Show Gist options
  • Save svalleru/2d88c72f49c24ceece2b433b17ccd113 to your computer and use it in GitHub Desktop.
Save svalleru/2d88c72f49c24ceece2b433b17ccd113 to your computer and use it in GitHub Desktop.
Graph Traversal
# A -> B
# A -> C
# B -> C
# B -> D
# C -> D
# D -> C
# E -> F
# F -> C
graph = {
'A': ['B', 'C'],
'B': ['C', 'D'],
'C': ['D'],
'D': ['C'],
'E': ['F'],
'F': ['C']
}
def all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if start not in graph.keys():
return []
paths = []
for node in graph[start]:
if node not in path:
newpaths = all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
print 'All paths from A to D: ', all_paths(graph, 'A', 'D')
print 'Shortest path from A to D: ', sorted(all_paths(graph, 'A', 'D'))[-1]
# All paths from A to D: [['A', 'B', 'C', 'D'], ['A', 'B', 'D'], ['A', 'C', 'D']]
# Shortest path from A to D: ['A', 'C', 'D']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment