Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import deque
- def find_shortest_path(graph, source, destination):
- qu = deque([source])
- visited = {source}
- parent = {source: None}
- while qu:
- node = qu.popleft()
- if node == destination:
- break
- for child in graph[node]:
- if child in visited:
- continue
- visited.add(child)
- qu.append(child)
- parent[child] = node
- return parent
- def find_size(parent, destination):
- size = 0
- node = destination
- while node is not None:
- size += 1
- node = parent[node]
- return size -1
- nodes = int(input())
- pairs = int(input())
- graph = {}
- for _ in range(nodes):
- node_str, children_str = input().split(':')
- node = int(node_str)
- children = [int(x) for x in children_str.split()] if children_str else []
- graph[node] = children
- for _ in range(pairs):
- source, destination = [int(x) for x in input().split('-')]
- parent = find_shortest_path(graph, source, destination)
- if destination not in parent:
- print(f'{{{source}, {destination}}} -> -1')
- continue
- size = find_size(parent, destination)
- print(f'{{{source}, {destination}}} -> {size}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement