Matrix Reachability

View as PDF

Submit solution


Points: 100
Time limit: 1.0s
PyPy 3 2.0s
Python 3 2.0s
Memory limit: 500M

Problem type

You are given a directed graph with vertices numbered from 1 to n. The graph is described by its adjacency matrix: the entry in row i and column j is 1 if there is a directed edge from vertex i to vertex j, and 0 otherwise.

Starting at vertex s, determine every vertex that can be reached by following zero or more directed edges.

Input

The first line contains two integers n and s, the number of vertices and the starting vertex.

The next n lines each contain n integers. The j-th integer on the i-th of these lines is the adjacency matrix entry for the directed edge from vertex i to vertex j.

Output

Output one line containing all reachable vertices in increasing order, separated by spaces.

Constraints

  • 1 \le n \le 500
  • 1 \le s \le n
  • Each matrix entry is either 0 or 1.

Example 1

Input
4 1
0 1 1 0
0 0 0 1
0 0 0 0
0 0 1 0
Output
1 2 3 4
Explanation

From vertex 1, we can directly reach vertices 2 and 3. From vertex 2, we can reach vertex 4, so all vertices are reachable.

Example 2

Input
5 3
0 0 0 0 0
1 0 0 0 0
0 0 0 1 0
0 0 0 0 1
0 0 0 0 0
Output
3 4 5
Explanation

Starting at vertex 3, the only new vertices reachable are 4 and then 5.


Comments

There are no comments at the moment.