@@ -11,53 +11,39 @@ def __init__(self, graph):
11
11
self .graph = graph
12
12
13
13
def find_path (self , start , end , path = None ):
14
- self .start = start
15
- self .end = end
16
- self .path = path if path else []
14
+ path = path or []
17
15
18
- self .path += [self .start ]
19
- if self .start == self .end :
20
- return self .path
21
- if self .start not in self .graph :
22
- return None
23
- for node in self .graph [self .start ]:
24
- if node not in self .path :
25
- newpath = self .find_path (node , self .end , self .path )
16
+ path .append (start )
17
+ if start == end :
18
+ return path
19
+ for node in self .graph .get (start , []):
20
+ if node not in path :
21
+ newpath = self .find_path (node , end , path )
26
22
if newpath :
27
23
return newpath
28
- return None
29
24
30
25
def find_all_path (self , start , end , path = None ):
31
- self .start = start
32
- self .end = end
33
- _path = path if path else []
34
- _path += [self .start ]
35
- if self .start == self .end :
36
- return [_path ]
37
- if self .start not in self .graph :
38
- return []
26
+ path = path or []
27
+ path .append (start )
28
+ if start == end :
29
+ return [path ]
39
30
paths = []
40
- for node in self .graph [self .start ]:
41
- if node not in _path :
42
- newpaths = self .find_all_path (node , self .end , _path [:])
43
- for newpath in newpaths :
44
- paths .append (newpath )
31
+ for node in self .graph .get (start , []):
32
+ if node not in path :
33
+ newpaths = self .find_all_path (node , end , path [:])
34
+ paths .extend (newpaths )
45
35
return paths
46
36
47
37
def find_shortest_path (self , start , end , path = None ):
48
- self .start = start
49
- self .end = end
50
- _path = path if path else []
38
+ path = path or []
39
+ path .append (start )
51
40
52
- _path += [self .start ]
53
- if self .start == self .end :
54
- return _path
55
- if self .start not in self .graph :
56
- return None
41
+ if start == end :
42
+ return path
57
43
shortest = None
58
- for node in self .graph [ self . start ] :
59
- if node not in _path :
60
- newpath = self .find_shortest_path (node , self . end , _path [:])
44
+ for node in self .graph . get ( start , []) :
45
+ if node not in path :
46
+ newpath = self .find_shortest_path (node , end , path [:])
61
47
if newpath :
62
48
if not shortest or len (newpath ) < len (shortest ):
63
49
shortest = newpath
0 commit comments