Matrix Reachability
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≤n≤500
- 1≤s≤n
- Each matrix entry is either
0or1.
Example 1
4 1
0 1 1 0
0 0 0 1
0 0 0 0
0 0 1 0
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
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
3 4 5
Explanation
Starting at vertex 3, the only new vertices reachable are 4 and then 5.
Comments0
No comments yet
Be the first to comment.
New comment
Log in to join the discussion.