我试图创建图形的帮助下面的链接,但是当我使用find_path方法我得到不正确的路径返回。链接:图表为什么找不到正确的路径?
http://www.python-course.eu/graphs_python.php
代码:
class Graph(object):
def __init__(self, graph_dict=None):
""" initializes a graph object
If no dictionary or None is given, an empty dictionary will be used
"""
if graph_dict is None:
graph_dict = {}
self.__graph_dict = graph_dict
def find_path(self, start_vertex, end_vertex, path=[]):
""" find a path from start_vertex to end_vertex
in graph """
graph = self.__graph_dict
path = path + [start_vertex]
if start_vertex == end_vertex:
return path
if start_vertex not in graph:
return None
for vertex in graph[start_vertex]:
if vertex not in path:
extended_path = self.find_path(vertex,
end_vertex,
path)
if extended_path:
return extended_path
return None
g = {"a": ["c", "d"],
"b": ["a", "c"],
"c": ["a", "b", "c", "d", "e"],
"d": ["c", "e"],
"e": ["c", "f"],
"f": ["c"]
}
graph = Graph(g)
"""
graph:
a<----b <-- one way
|\ / --- two way
| \/
| c <-- f
|/\ ^
v/ \ |
d---->e--/
"""
print graph.find_path("b", "f")
Output: ['b', 'a', 'c', 'd', 'e', 'f']
Should be: ['b', 'a', 'd', 'e', 'f']
什么是错在Graph类find_path方法?
Djikstra的算法工作。谢谢你的回答。 – Hsin