Pathfinding
InterviewTime limit1sMemory limit128 MB
Given a directed graph as an adjacency matrix and a start node, print the nodes first reached at each successive distance using BFS.
Problem
Bessie is stranded on a deserted arctic island and wants to work out every route she could take back to her pasture. She has tested her boat and knows she can travel from one island to another in 1 unit of time whenever a current-driven route connects that ordered pair of islands.
She has mapped the ocean as single-hop routes between the () islands, numbered through . Routes are one-way (unidirectional), because the currents push the boat in a fixed direction. A pair of islands may be joined by two separate routes using opposite currents, giving an effectively bidirectional link. No route ever connects an island to itself.
Given her starting island () and the map, determine which islands are one hop away, which are two hops away, and so on. When several routes reach the same island, count only the shortest one.
For example, the following islands are connected as shown, with :
start--> 1-------->2
| |
| |
V V
4<--------3
Bessie reaches island 1 at time 0 (her start), islands 2 and 4 at time 1, and island 3 at time 2.
The map is given as a matrix , where the entry in row , column is (). means the currents let Bessie travel directly from island to island in one time unit. Row has entries .
Input
- Line 1: two space-separated integers and .
- Lines 2 to : line contains the space-separated integers of matrix row , namely .
Output
- For each time , print one line listing, in ascending order, every island Bessie can first reach at exactly time .
- Print a line only while such islands exist; stop as soon as no island is first reached at the next time. Islands unreachable from are never printed.