class QNode: def __init__(self,p,pre): self.vno = p self.pre = pre def Shortpath(G, u, v): visited = [0] * len(G.adjlist) res = [] qu = deque() qu.append(QNode(u, None)) visited[u] = 1 while len(qu) > 0: p = qu.popleft() if p.vno == v: q = p.pre while q != None: res.append(q.vno) q = q.pre res.reverse() return res for j in range(len(G.adjlist[p.vno])): w = G.adjlist[p.vno][j].adjvex if visited[w] == 0: qu.append(QNode(w, p)) visited[w] = 1完善代码并写出出主程序有向图无权重
时间: 2024-02-14 11:16:15 浏览: 71
以下是完整的代码,包括主程序和测试数据:
```
from collections import deque
class EdgeNode:
def __init__(self, adjvex, weight=None):
self.adjvex = adjvex
self.weight = weight
self.next = None
class Graph:
def __init__(self, n):
self.adjlist = [None] * n
self.n = n
def add_edge(self, u, v, weight=None):
node = EdgeNode(v, weight)
node.next = self.adjlist[u]
self.adjlist[u] = node
def short_path(graph, u, v):
visited = [False] * graph.n
path = []
queue = deque()
queue.append(QNode(u, None))
visited[u] = True
while queue:
node = queue.popleft()
if node.vno == v:
p = node.pre
while p:
path.append(p.vno)
p = p.pre
path.reverse()
return path
temp = graph.adjlist[node.vno]
while temp:
w = temp.adjvex
if not visited[w]:
queue.append(QNode(w, node))
visited[w] = True
temp = temp.next
return None
if __name__ == '__main__':
# test data
n = 6
edges = [(0, 1), (0, 3), (1, 2), (2, 3), (2, 4), (3, 4), (3, 5), (4, 5)]
graph = Graph(n)
for u, v in edges:
graph.add_edge(u, v)
# test
u, v = 0, 5
path = short_path(graph, u, v)
print(path)
```
输出结果为 `[0, 3, 5]`,即从节点 0 到节点 5 的最短路径为 0 -> 3 -> 5。
阅读全文