您能找出我的BFS代码中的错误

问题描述 投票:-1回答:1

问题:通过使用BFS查找路径,以通过共同的朋友将消息从Sara发送到Uzma此代码给出了错误,但未显示路径。你能找出错误吗?注意:邻居是给定节点的朋友

import collections

class Node():
    #dictionary is use to make graph
    graph={} 
    def add_edge(self,node,neighbour):
        if node not in self.graph.keys():
            self.graph[node]=[neighbour]
        else:
            self.graph[node].append(neighbour)

    def show_graph(self):
        print(self.graph)

    def show_neigh(self,node):
        print(self.graph[node])

    def BFS(self,initial,final):
        visited,queue=set(), collections.deque([initial])
        visited.add(initial)
        while queue:
            vertex=queue.popleft()
            for adj in self.graph[vertex]:
                if adj == final:
                    visited.add(adj)
                    print("Message sent Successfully !",visited)
                    break
                if adj not in visited:
                    visited.add(adj)
                    queue.append(adj)

g=Node()
g.add_edge("Amina","Sara")
g.add_edge("Amina","Riaz")
g.add_edge("Riaz","Ali")
g.add_edge("Riaz","Ahmed")
g.add_edge("Ahmed","Ahsan")
g.add_edge("Ahmed","Amina")
g.add_edge("Rida","Taha")
g.add_edge("Rida","Hassan")
g.add_edge("Uzma","Taha")
g.add_edge("Uzma","Ahsan")

g.show_graph()
g.BFS("Sara","Uzma")
python breadth-first-search
1个回答
0
投票

[Sara永远不会添加到图的节点:它仅添加到Anima的邻居。

© www.soinside.com 2019 - 2024. All rights reserved.