@@ -10,10 +10,10 @@ class GraphSearch:
1010def __init__ (self , graph ):
1111self .graph = graph
1212
13- def find_path (self , start , end , path = [] ):
13+ def find_path (self , start , end , path = None ):
1414self .start = start
1515self .end = end
16- self .path = path
16+ self .path = path if path else []
1717
1818self .path += [self .start ]
1919if self .start == self .end :
@@ -27,37 +27,37 @@ def find_path(self, start, end, path=[]):
2727return newpath
2828return None
2929
30- def find_all_path (self , start , end , path = [] ):
30+ def find_all_path (self , start , end , path = None ):
3131self .start = start
3232self .end = end
33- self . path = path
34- self . path += [self .start ]
33+ _path = path if path else []
34+ _path += [self .start ]
3535if self .start == self .end :
36- return [self . path ]
36+ return [_path ]
3737if self .start not in self .graph :
3838return []
3939paths = []
4040for node in self .graph [self .start ]:
41- if node not in self . path :
42- newpaths = self .find_all_path (node , self .end , self . path )
41+ if node not in _path :
42+ newpaths = self .find_all_path (node , self .end , _path [:] )
4343for newpath in newpaths :
4444paths .append (newpath )
4545return paths
4646
47- def find_shortest_path (self , start , end , path = [] ):
47+ def find_shortest_path (self , start , end , path = None ):
4848self .start = start
4949self .end = end
50- self . path = path
50+ _path = path if path else []
5151
52- self . path += [self .start ]
52+ _path += [self .start ]
5353if self .start == self .end :
54- return self . path
54+ return _path
5555if self .start not in self .graph :
5656return None
5757shortest = None
5858for node in self .graph [self .start ]:
59- if node not in self . path :
60- newpath = self .find_shortest_path (node , self .end , self . path )
59+ if node not in _path :
60+ newpath = self .find_shortest_path (node , self .end , _path [:] )
6161if newpath :
6262if not shortest or len (newpath ) < len (shortest ):
6363shortest = newpath
@@ -82,5 +82,5 @@ def find_shortest_path(self, start, end, path=[]):
8282
8383### OUTPUT ###
8484# ['A', 'B', 'C', 'D']
85- # [['A', 'B', 'C', 'D']]
86- # ['A', 'B', 'C', ' D']
85+ # [['A', 'B', 'C', 'D'], ['A', 'B', 'D'], ['A', 'C', 'D'] ]
86+ # ['A', 'B', 'D']
0 commit comments