Matrix Reachability
View as PDFYou are given a directed graph with vertices numbered from to
. The graph is described
by its adjacency matrix: the entry in row
and column
is
1 if there is a directed edge
from vertex to vertex
, and
0 otherwise.
Starting at vertex , determine every vertex that can be reached by following zero or more
directed edges.
Input
The first line contains two integers and
, the number of vertices and the starting vertex.
The next lines each contain
integers. The
-th integer on the
-th of these lines is
the adjacency matrix entry for the directed edge from vertex
to vertex
.
Output
Output one line containing all reachable vertices in increasing order, separated by spaces.
Constraints
- Each matrix entry is either
0or1.
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 , we can directly reach vertices
and
. From vertex
, we can reach
vertex
, 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 , the only new vertices reachable are
and then
.
Comments