已知图中的两个结点的指针DirectedGraphNode* a和DirectedGraphNode* b(请不要在意数据类型,图是有向图),判断两点间是否存在一条路径并返回bool值,代表是否存在(a到b或b到a)。
# write code here
def helper(a,b):
queue = [a]
visited = set()
while queue:
pop = queue.pop(0)
if pop==b: return True
if pop not in visited:visited.add(pop)
for i in pop.neighbors:
if i not in visited:
queue.append(i)
return False
return helper(a,b) or helper(b,a)
# -*- coding:utf-8 -*-
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = []
class Path:
# 递归 深度优先遍历
def judge(self, start, end, s):
for i in start.neighbors:
if i == end:
return True
if id(i) not in s:
s[id(i)] = 1
return self.judge(i, end, s)
return False
# 栈 广度优先遍历
def judgeStack(self, start, end, s):
stack = []
stack.append(start)
while stack:
node = stack.pop()
for i in node.neighbors:
if i == end:
return True
if id(i) not in s:
stack.append(i)
s[id(i)] = 1
return False
# 队列 广度优先遍历
def judgeQueue(self, start, end, s):
queue = []
queue.append(start)
while queue:
node = queue.pop(0)
for i in node.neighbors:
if i == end:
return True
if id(i) not in s:
queue.append(i)
s[id(i)] = 1
return False
def checkPath(self, a, b):
if a == b:
return True
visited = dict()
visited[id(a)] = 1
if self.judgeStack(a, b, visited):
return True
visited = dict()
visited[id(b)] = 1
if self.judgeStack(b, a, visited):
return True
return False