Pathfinding

Interview

Time limit1sMemory limit128 MB

Summary
Given a directed graph as an adjacency matrix and a start node, print the nodes first reached at each successive distance using BFS.
Level

Medium4 of 10

Topics
Graph, BFS
Solved
No attempts yet

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 NN (1≤N≤1001 \le N \le 100) islands, numbered 11 through NN. 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 MM (1≤M≤N1 \le M \le N) 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 N=4N = 4 islands are connected as shown, with M=1M = 1:

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 CC, where the entry in row rr, column cc is CrcC_{rc} (0≤Crc≤10 \le C_{rc} \le 1). Crc=1C_{rc} = 1 means the currents let Bessie travel directly from island rr to island cc in one time unit. Row rr has NN entries Cr1,…,CrNC_{r1}, \dots, C_{rN}.

Input

  • Line 1: two space-separated integers NN and MM.
  • Lines 2 to N+1N+1: line r+1r+1 contains the NN space-separated integers of matrix row rr, namely Cr1,…,CrNC_{r1}, \dots, C_{rN}.

Output

  • For each time i=0,1,2,…i = 0, 1, 2, \dots, print one line listing, in ascending order, every island Bessie can first reach at exactly time ii.
  • Print a line only while such islands exist; stop as soon as no island is first reached at the next time. Islands unreachable from MM are never printed.

Examples3

  1. Example 1

    Input
    4 1
    0 1 0 1
    0 0 1 0
    0 0 0 1
    0 0 0 0
    
    Expected output
    1
    2 4
    3
    
  2. Example 2

    Input
    1 1
    0
    
    Expected output
    1
    
  3. Example 3

    Input
    5 1
    0 1 0 0 0
    0 0 1 0 0
    0 0 0 1 0
    0 0 0 0 1
    0 0 0 0 0
    
    Expected output
    1
    2
    3
    4
    5