LintCode Q176 Route Between Two Nodes in Graph dfs in Python

  • Jinhai ZHOU
  • 4 Minutes
  • 2016年11月13日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Definition for a Directed graph node
# class DirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = []
from collections import deque
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
# time complexity O(N)
# Total Runtime: 785 ms
# 100% test cases passed.
# DFS
visited = {}
for x in graph:
visited[x] = False
return self.dfs(s, visited, t)
def dfs(self, i, visited, t):
if i == t:
return True
visited[i] = True
for j in i.neighbors:
if not visited[j] and self.dfs(j, visited, t):
return True
return False
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。