# Stopping BFS traversal after reachin a certain depth in RGL

**URL:** <https://www.ruby-forum.com/t/stopping-bfs-traversal-after-reachin-a-certain-depth-in-rgl/131239>\
**Category:** Rails\
**Created:** [March 7, 2008, 6:18am UTC](https://www.ruby-forum.com/t/stopping-bfs-traversal-after-reachin-a-certain-depth-in-rgl/131239 "2008-03-07T06:18:19Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![sgudibanda](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/a9adbd/32.png) [@sgudibanda](https://www.ruby-forum.com/u/sgudibanda)\
**Post date:** [March 7, 2008, 6:18am UTC](https://www.ruby-forum.com/t/stopping-bfs-traversal-after-reachin-a-certain-depth-in-rgl/131239/1 "2008-03-07T06:18:19Z")

</div>

Hi,

I am using RGL for some of the graph implementations. My requirements is  
such that I need to find out all nodes that are at distance less than  
3 from root.

For this, I thought of traversing the graph using BFS and stop the  
traversal when i reach 4th level. But how do I do this?

regards,  
Sandeep G

---

<div class="post-metadata">

**Author:** ![sgudibanda](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/a9adbd/32.png) [@sgudibanda](https://www.ruby-forum.com/u/sgudibanda)\
**Post date:** [March 12, 2008, 12:15am UTC](https://www.ruby-forum.com/t/stopping-bfs-traversal-after-reachin-a-certain-depth-in-rgl/131239/2 "2008-03-12T00:15:42Z")

</div>

On 7 Mrz., 06:18, Sandeep G. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> Hi,
> 
> I am usingRGLfor some of the graph implementations. My requirements is  
> such that I need to find out all nodes that are at distance less than  
> 3 from root.
> 
> For this, I thought of traversing the graph using BFS and stop the  
> traversal when i reach 4th level. But how do I do this?

Take the example graph from the README  
[http://rgl.rubyforge.org/rgl/index.html:](http://rgl.rubyforge.org/rgl/index.html:)

require ‘rgl/adjacency’  
require ‘rgl/traversal’

dg = RGL::DirectedAdjacencyGraph[1,2 ,2,3 ,2,4, 4,5, 6,4, 1,6]  
bfs = dg.bfs\_iterator(1)  
bfs.attach\_distance\_map  
bfs.each do |v|  
dist = bfs.distance\_to\_root(v)  
break if dist \> 3  
print v, ': ', dist, “\n”  
end

Should produce this result:

1: 1  
6: 2  
2: 2  
4: 3  
3: 3

Regards  
Horst
