-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path618.search-graph-nodes.py
42 lines (32 loc) · 1.14 KB
/
618.search-graph-nodes.py
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
38
39
40
41
42
"""
Definition for a undirected graph node
class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
"""
class Solution:
"""
@param: graph: a list of Undirected graph node
@param: values: a hash mapping, <UndirectedGraphNode, (int)value>
@param: node: an Undirected graph node
@param: target: An integer
@return: a node
"""
def searchNode(self, graph, values, node, target):
# write your code here
if node is None or len(graph) == 0 or len(values) == 0:
return None
queue = [node]
visited = set([node])
while (len(queue) > 0):
size = len(queue)
for i in range(size):
tmp = queue.pop(0)
if values[tmp] == target:
return tmp
for neighbor in tmp.neighbors:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return None