欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

无向图的深度优先搜索和广度优先搜索实现(python)

程序员文章站 2022-03-03 11:50:51
...
class UndirectedGraphNode:
    def __init__(Self,x):
        self.label=x
        self.neighbors=[]
#寻找某一点到另外一点的路径
class Path:
    def  DFS(self,startNode,endNode,s): # s 保存经过节点的字典变量
        for i in startNode.neighbors:
            if i==endNode:
                return True
            if not in s:
                s[id(i)]=1
                return self.DFS(i,endNode,s)
       return False
    def BFS(self,startNode,endNode,s):
        stack=[starNode]
        while stack:
            current=stack.pop()
            for i in current.neighbors:
                if i==endNode:
                    return True
                if i not in s:
                    s[id(i)]=1
                    stack.append(i)
        return False