我正在实现一个图类,并且想编写一个确定给定路径是否存在的函数。
我的图表示为{a:{b:c}},其中a和b是相互连接的顶点,c是边缘的权重。 这是一个无方向图。我想为无向图实现我的dos_path_exist()函数。目前,它的计算就好像我的图是有向图的。
给出:
{0: {1: 5.0, 2: 10.0}, 1: {3: 3.0, 4: 6.0}, 3: {2: 2.0, 4: 2.0, 5: 2.0}, 4: {6: 6.0}, 5: {6: 2.0}, 7: {9: 1.0}, 8: {7: 2.0, 9: 4.0}}
存在从顶点2到3的路径。由于我的函数是定向的,因此它返回False。
class Graph:
def __init__(self, n):
"""
Constructor
:param n: Number of vertices
"""
self.order = n
self.size = 0
self.vertex = {}
def insert_edge(self, u, v, w): #works fine
if u in self.vertex and v < self.order:
if not v in self.vertex[u]:
self.vertex[u][v] = w
self.size += 1
elif u not in self.vertex and u < self.order and v < self.order:
self.vertex[u] = {}
self.vertex[u][v] = w
self.size += 1
else:
raise IndexError
def does_path_exist(self, u, v): #works for directed graph, but not non-directed graph
if u >= self.order or v >= self.order:
raise IndexError
if u == v:
return True
stac = []
stac.append(u)
visited = []
while len(stac) != 0:
u = stac.pop(0)
if u not in visited:
if u == v:
return True
visited.append(u)
if u in self.vertex:
t = self.vertex[u]
else:
break
a = t.keys()
for u in a:
if u not in visited:
stac.append(u)
return False
我的主要功能:
def main():
g = Graph(10)
g.insert_edge(0,1,5.0)
g.insert_edge(0,2,10.0)
g.insert_edge(1,3,3.0)
g.insert_edge(1,4,6.0)
g.insert_edge(3,2,2.0)
g.insert_edge(3,4,2.0)
g.insert_edge(3,5,2.0)
g.insert_edge(4,6,6.0)
g.insert_edge(5,6,2.0)
g.insert_edge(7,9,1.0)
g.insert_edge(8,7,2.0)
g.insert_edge(8,9,4.0)
print(g.vertex)
print(g.does_path_exist(2,3)) #returns False but should return True
if __name__ == '__main__':
main()
答案 0 :(得分:3)
您的循环仅检查出线边缘。如果您给它u=2
,它将不会从2
找到传出的边,因此它会在一次迭代后结束。
您需要:
insert_edge()
的两个方向上添加有向边。 insert_edge()
需要做更多的工作,并且会占用更多的内存。does_edge_exist()
中的计算量大为增加。答案 1 :(得分:0)
您提到该图是有向图,但是您仅在u
函数中将边缘从v
分配给insert_edge
。我更新了该函数,以便它也将边缘v
分配给u
,并返回True
作为测试输入。
def insert_edge(self, u, v, w): #works fine
# Allow to travel from u to v
if u in self.vertex and v < self.order:
if not v in self.vertex[u]:
self.vertex[u][v] = w
self.size += 1
elif u not in self.vertex and u < self.order and v < self.order:
self.vertex[u] = {}
self.vertex[u][v] = w
self.size += 1
else:
raise IndexError
# Allow travel to v from u
if v in self.vertex and u < self.order:
if not u in self.vertex[v]:
self.vertex[v][u] = w
elif v not in self.vertex and v < self.order and u < self.order:
self.vertex[v] = {}
self.vertex[v][u] = w
else:
raise IndexError