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

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)

你可能感兴趣的:(LintCode:图中两个点之间的路线)