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

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

 

你可能感兴趣的:(无向图的深度优先搜索和广度优先搜索实现(python))