Find all reachable nodes in a graph
Mathematica 63 40 37
My earlier submission was incorrect. I had misinterpreted what ConnectedComponents
returns. The present approach relies on Belisarius' suggestion to useVertexOutComponent
. 3 additional chars saved by alephalpha.
The following generates an 11 by 11 adjacency matrix of 0's and 1's, where 1 indicates that the vertex with the row number is connected directly to the vertex corresponding to column number of the cell. (SeedRandom
ensures that your matrix a
will match mine.)
SeedRandom[21]
a = Array[RandomChoice[{0.9, 0.1} -> {0, 1}] &, {11, 11}];
Example
(37 chars)
AdjacencyGraph@a~VertexOutComponent~4
{4, 1, 7, 8, 9, 3}
Verifying
The directed graph displays how to reach vertices {1, 7, 8, 9, 3}
from vertex 4.
AdjacencyGraph[a, ImagePadding -> 30, VertexLabels -> "Name"]
Python 2.7 - 80 65
def R(G,s):
k=a={s}
while k:a=a|k;k|=set(G[k.pop()])-a
print a
GolfScript, 27 24 characters
{:G,{G{1$&},{)||}/}*}:C;
This code implements the operator C
which takes starting node and graph on the stack and leaves a list of reachable notes on the stack after execution.
Example (online):
[1] [[1 [2 3]][2 [3]][3 [1]][4 [2]]] C
# returns [1 2 3]