我在此网站上使用了以下代码: https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/
我应该做的是允许用户在节点之间添加边。
from collections import defaultdict
import time
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def DFSUtil(self,v,visited):
visited[v]= True
print (v)
for i in self.graph[v]:
if visited[i] == False:
self.DFSUtil(i, visited)
def DFS(self, v):
visited = [False]*(len(self.graph))
self.DFSUtil(v,visited)
g = Graph()
# My way of adding edges -
v = int(input("Enter a number for v: "))
w = int(input("Enter a number for W: "))
g.addEdge(v, w)
v = int(input("Enter a number for v: "))
w = int(input("Enter a number for w: "))
g.addEdge(v, w)
v = int(input("Enter a number for v: "))
w = int(input("Enter a number for w: "))
g.addEdge(v, w)
v = int(input("Enter a number for v: "))
w = int(input("Enter a number for w: "))
g.addEdge(v, w)
v = int(input("Enter a number for v: "))
w = int(input("Enter a number for w: "))
g.addEdge(v, w)
v = int(input("Enter a number for v: "))
w = int(input("Enter a number for w: "))
g.addEdge(v, w)
# Original way of adding edges -
# g.addEdge(0, 1)
# g.addEdge(0, 2)
# g.addEdge(1, 2)
# g.addEdge(2, 0)
# g.addEdge(2, 3)
# g.addEdge(3, 3)
print ("Following is Depth First Traversal" " (starting from vertex 2)")
g.DFS(2)
在代码中,我为执行方法和原始方法添加了注释。
这是我遇到问题的地方:
我这样做的方式:我让用户输入边缘。但是,当我使用不同的数字运行它时,它要么搜索一个数字,要么说索引超出范围。
我已经尝试解决了两天,但我没有运气。任何帮助表示赞赏!
答案 0 :(得分:1)
DFS方法正在创建一个列表,该列表的长度与图形中非叶节点的数量相同,我将其称为N,然后DFSUtil方法通过节点号对其进行索引。仅当每个节点的编号都在0到N-1之间时,这才起作用。如果您的用户要输入任意数字(用户通常会输入该数字),那么在DFS中将访问的字典设置为更安全:
visited = {}
for parent in self.graph:
visited[parent] = False
for child in self.graph[parent]:
visited[child] = False