You can avoid using recursion using an advancing wavefront algorithm (breadth first search) on the nodes. Here's an outline of the algorithm, it's a small adaptation to make it work for edges:
- Track topological distances using a dictionary
top_dist
which is initially empty. - Let
dist = 0
- Put the initial nodes in set
wavefront
. - Set
top_dist[node] = dist
for each node inwavefront
. - For each node adjacent to
wavefront
that is not intop_dist
, add that node to setnext_wavefront
. - Increment
dist
- Set
wavefront = next_wavefront
- Repeat from 4 until no further nodes are reachable.
If some nodes remain unvisited, the graph has multiple weak components.
If the initial nodes in step 3 are the endpoints of your initial edge, then you can use the top_dist
map on the edge's nodes to get distances to the edges. I think a useful definition of distance to an edge is min(top_dist(e1), top_dist(e2)) + 1
. Now that you have a distance to each edge, you can grab the closest 2000.
This algorithm is O(|N|+|E|) -- linear on the sum of the number of edges and nodes.