LintCode Q176 Route Between Two Nodes in Graph bfs 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
33
34
35
36
37
# 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: 545 ms
# 100% test cases passed.
# BFS
if s == t:
return True
# initialize
visited = {}
for node in graph:
visited[node] = False
q = deque()
q.append(s)
while q:
node = q.popleft()
visited[node] = True
if t == node:
return True
else:
for n in node.neighbors:
if not visited[n]:
q.append(n)
return False
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。