@@ -53,41 +53,81 @@ def find_shortest_path_bfs(self, start, end):
53
53
dist_to = {start : 0 }
54
54
edge_to = {}
55
55
56
+ if start == end :
57
+ return queue
58
+
56
59
while len (queue ):
57
60
value = queue .pop (0 )
58
61
for node in self .graph [value ]:
59
62
if node not in dist_to .keys ():
60
63
edge_to [node ] = value
61
64
dist_to [node ] = dist_to [value ] + 1
62
65
queue .append (node )
63
- if end in edge_to .values ():
64
- break
65
-
66
- path = []
67
- node = end
68
- while dist_to [node ] != 0 :
69
- path .insert (0 , node )
70
- node = edge_to [node ]
71
- path .insert (0 , start )
72
- return path
66
+ if end in edge_to .keys ():
67
+ path = []
68
+ node = end
69
+ while dist_to [node ] != 0 :
70
+ path .insert (0 , node )
71
+ node = edge_to [node ]
72
+ path .insert (0 , start )
73
+ return path
73
74
74
75
75
76
def main ():
76
77
"""
77
78
# example of graph usage
78
- >>> graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], 'F': ['C']}
79
+ >>> graph = {
80
+ ... 'A': ['B', 'C'],
81
+ ... 'B': ['C', 'D'],
82
+ ... 'C': ['D', 'G'],
83
+ ... 'D': ['C'],
84
+ ... 'E': ['F'],
85
+ ... 'F': ['C'],
86
+ ... 'G': ['E'],
87
+ ... 'H': ['C']
88
+ ... }
79
89
80
90
# initialization of new graph search object
81
- >>> graph1 = GraphSearch(graph)
91
+ >>> graph_search = GraphSearch(graph)
82
92
83
- >>> print(graph1 .find_path_dfs('A', 'D'))
93
+ >>> print(graph_search .find_path_dfs('A', 'D'))
84
94
['A', 'B', 'C', 'D']
85
- >>> print(graph1.find_all_paths_dfs('A', 'D'))
95
+
96
+ # start the search somewhere in the middle
97
+ >>> print(graph_search.find_path_dfs('G', 'F'))
98
+ ['G', 'E', 'F']
99
+
100
+ # unreachable node
101
+ >>> print(graph_search.find_path_dfs('C', 'H'))
102
+ None
103
+
104
+ # non existing node
105
+ >>> print(graph_search.find_path_dfs('C', 'X'))
106
+ None
107
+
108
+ >>> print(graph_search.find_all_paths_dfs('A', 'D'))
86
109
[['A', 'B', 'C', 'D'], ['A', 'B', 'D'], ['A', 'C', 'D']]
87
- >>> print(graph1 .find_shortest_path_dfs('A', 'D'))
110
+ >>> print(graph_search .find_shortest_path_dfs('A', 'D'))
88
111
['A', 'B', 'D']
89
- >>> print(graph1.find_shortest_path_bfs('A', 'D'))
112
+ >>> print(graph_search.find_shortest_path_dfs('A', 'F'))
113
+ ['A', 'C', 'G', 'E', 'F']
114
+
115
+ >>> print(graph_search.find_shortest_path_bfs('A', 'D'))
90
116
['A', 'B', 'D']
117
+ >>> print(graph_search.find_shortest_path_bfs('A', 'F'))
118
+ ['A', 'C', 'G', 'E', 'F']
119
+
120
+ # start the search somewhere in the middle
121
+ >>> print(graph_search.find_shortest_path_bfs('G', 'F'))
122
+ ['G', 'E', 'F']
123
+
124
+ # unreachable node
125
+ >>> print(graph_search.find_shortest_path_bfs('A', 'H'))
126
+ None
127
+
128
+ # non existing node
129
+ >>> print(graph_search.find_shortest_path_bfs('A', 'X'))
130
+ None
91
131
"""
92
132
93
133
0 commit comments