如何在这段代码中实现“广度优先搜索”?

2024-10-03 06:30:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在下面的代码中实现“乳房优先搜索”

它不起作用,因为我脑子里有个错误

是的

回溯(最近一次呼叫):

文件“”,第1行,在 runfile('C:/Users/psh93/.spyder-py3/width\u First\u Search.py',wdir='C:/Users/psh93/.spyder-py3')

runfile中的文件“D:\Anaconda\lib\site packages\spyder\u kernels\customize\spydercustomize.py”,第827行 execfile(文件名,命名空间)

execfile中的文件“D:\Anaconda\lib\site packages\spyder\u kernels\customize\spydercustomize.py”,第110行 exec(compile(f.read(),filename,'exec'),命名空间)

文件“C:/Users/psh93/.spyder-py3/width\u First\u Search.py”,第51行,in 图BFS(1)

文件“C:/Users/psh93/.spyder-py3/width\u First\u Search.py”,第33行,在BFS中 queue.append(self.E[n])

TypeError:无法处理的类型:“list”

是的

这是我的密码

class Vertex:

    def __init__(self, ID=0, data=None):
        self.id = ID
        self.data = data
        self.Visited = False

class Graph:

    def __init__(self):
        self.V = {}
        self.E = {}

    def addVertex(self, vertex=None):
        if vertex == None: return

        self.V[vertex.id] = vertex
        self.E[vertex.id] = []

    def addEdge(self, start_id=None, end_id=None):
        if start_id == None or end_id == None: return

        self.E[start_id].append(end_id)

    def BFS(self, first):
        #queue = [first]
        #visited = []

        #while queue:
            #n = queue.pop(0)
            #if n not in visited:
                #visited.append(n)
                #queue.append(self.E[n])

        #print(visited)

if __name__ == '__main__':

    graph = Graph()

    vertices = [(1, "A"), (2, "B"), (3, "C"), (4, "D"), (5, "E"), (6, "F"), (7, "G")]
    edges = [(1,2), (1,3), (2,4), (2,5), (3,4), (3,6), (4,5), (4,7), (5,7), (6,7)]

    for (idx, data) in vertices:
        v = Vertex(idx, data)
        graph.addVertex(v)

    for (s, e) in edges:
        graph.addEdge(s, e)

    graph.BFS(1)

标有#的区域就是问题所在

def BFS(self, first)

除BFS外无触摸码

输出

graph.BFS(1)

我想要1>;2>;3>;4>;5>;6>;七

我该怎么办

感谢您阅读长代码


Tags: 文件pygtselfnoneiddataqueue