无向图的深度优先搜索和广度优先搜索实现(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
上一篇: 优先查询条件
下一篇: 优秀开源Web开发资源大集合