forked from e-tinkers/mrt_map
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.py
More file actions
53 lines (44 loc) · 1.31 KB
/
graph.py
File metadata and controls
53 lines (44 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import json
def load_graph(file_name):
with open(file_name) as f:
data = json.load(f)
return data
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if start not in list(graph.keys()):
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath:
return newpath
return None
def all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if start not in list(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
def shortest_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if start not in list(graph.keys()):
return None
shortest = None
for node in graph[start]:
if node not in path:
new_path = shortest_path(graph, node, end, path)
if new_path:
if not shortest or len(new_path) < len(shortest):
shortest = new_path
return shortest