给出了一个没有多个边和环的无向图。该程序给出了这个错误:
File "dfsbfs.py", line 12, in dfs
new_vertices = [j for j in adj[u] if j not in visited]
IndexError: list index out of range.
我不明白为什么会这样。
n = int(input('Vertices: '))
m = int(input('Edges: '))
adj = []
for i in range(m):
adj.append(list(map(int, input().split())))
def dfs(v):
visited = {v}
to_explore = [v]
while to_explore:
u = to_explore.pop()
print (u)
new_vertices = [j for j in adj[u] if j not in visited]
to_explore.extend(new_vertices)
visited.update(new_vertices)
dfs(0)
您
to_explore有一个仍然需要访问的峰的列表。inadj是顶点之间的边列表,当您从中获取顶点to_explore索引并访问该索引时,如果您的顶点多于边,则该索引超出边列表。adjadj我不明白如何专门修复你的算法,但你至少需要:
之后,处理算法会更容易,只需在操作数据时将其对齐,使顶点对顶点,边对边。