要了解广度优先搜索,我观看了许多视频。然后,我在GeeksForGeeks
上找到了python代码但是我注意到当我删除该行时
g.addEdge(2, 0)
来自代码,输出限制为2, 3
这是正确的吗,还是BFS方法也应该向上移动并因此找到节点0和1?如果是这样,我认为defaultdict
方法对BFS不理想吗?
这是GeeksForGeeks的代码
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def BFS(self, s):
visited = [False] * (len(self.graph))
queue = []
queue.append(s)
visited[s] = True
while queue:
s = queue.pop(0)
print (s, end = " ")
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
g.BFS(2)