Given a undirected graph with V nodes and E edges. All nodes numbered from 1...N
Node have 3 parameters:
The struct of Node looks like that:
class Node:
def __init__(self, value:int, key:int, child:list):
self.value = value
self.key = key
self.child = childThe question is, some edges (aka path) locked with some key. Try to start from node 1 and try to reach node N using keys which you can have traversing by neighbors.
Return True if it possible to reach Nth node in the graph, otherwise return False.
Example 1:
1/(1) means 1 value of node, (1) key in the node
/
(1)
/ means, you should unlock edge between 1 and 2 via key (1)
[1/(1)]
/ \
(1) (2)
/ \
[2/(2)] [3/(5)]
\
(5)
\
[4/(3)]
return TrueExample 2:
[4/(2)]
/(4)
[1/(3)] <- starting node
/(2) \(3)
[3/(4)] [2/(1)]
return False # it could be because there is no key to unclock path from node1 to node3Expected time complexity: O(E + V)
class Node:
def __init__(self, data, key, children):
self.data = data
self.key = key
self.children = children
def find_princess(N, graph, start_node):
queue = collections.deque([start_node])
keys, visited = set([start_node.key]), set([start_node])
while queue:
new_node_added = False
for node in queue:
if node.val == N:
return True
for neighbor in graph[node].children:
if neighbor.key in keys and neighbor not in visited:
queue.append(neighbor)
keys.add(neighbor.key)
visited.add(neighbor)
new_node_added = True
if not new_node_added:
break
return False