您的位置:首页 > 其它

LintCode:图中两个点之间的路线

2016-05-12 14:50 363 查看
LintCode:图中两个点之间的路线

Python

方法一:

# Definition for a Directed graph node
# class DirectedGraphNode:
#     def __init__(self, x):
#         self.label = x
#         self.neighbors = []

class Solution:
"""
@param graph: A list of Directed graph node
@param s: the starting Directed graph node
@param t: the terminal Directed graph node
@return: a boolean value
"""
def hasRoute(self, graph, s, t):
# write your code here
if len(graph) == 0:
return False
if s == t:
return True
L = s.neighbors
while len(L) != 0:
s = L[0]
if t in L:
return True
L.remove(s)
L = list(set(L + s.neighbors))
return False


方法二:

# Definition for a Directed graph node
# class DirectedGraphNode:
#     def __init__(self, x):
#         self.label = x
#         self.neighbors = []

class Solution:
"""
@param graph: A list of Directed graph node
@param s: the starting Directed graph node
@param t: the terminal Directed graph node
@return: a boolean value
"""
def hasRoute(self, graph, s, t):
# write your code here
if len(graph) == 0:
return False
if s == t:
return True
L = s.neighbors
ans = self.fun(L, s, t)
return ans

def fun(self, L, s, t):
if s == t:
return True
if len(L) == 0:
return False
L += s.neighbors
L = list(set(L))
s = L[0]
L.remove(s)
#        print [node.label for node in L]
return self.fun(L, s, t)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: