我最近开始学习图并尝试使用Python来实现它。使用默认字典创建图形的邻接列表,添加边,这似乎工作得很好。现在,当我尝试实现 DFS 代码时,程序不会终止。
这是我写的程序:
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u)
# Taking input from the user
g = Graph()
root = input("Enter the root node: ")
for _ in range(int(input("Enter number of edges: "))):
u,v = input().split()
g.addEdge(u,v)
adj_list = dict(g.graph)
# DFS traversal
path = set()
stack = []
stack.append(root)
while stack:
u = stack.pop()
if u not in path:
path.add(u)
if u not in adj_list: # for leaf nodes
continue
stack.extend(adj_list[u])
print(path)
这是输出:
Enter the root node: A
Enter number of edges: 3
A B
A C
B D
然后就卡住了。它不会接受任何输入,不会显示任何内容,我所能做的就是
ctrl+C
(键盘中断)来停止它。
我尝试对邻接列表进行硬编码,而不接受用户的输入,然后它似乎工作正常。但我无法理解为什么如果我接受用户的输入它就不起作用。我不能总是对图表进行硬编码,必须有一个解决方案。 请帮助我,除非我明白这段代码出了什么问题,否则我无法平静。