monora / rgl

RGL is a framework for graph data structures and algorithms in Ruby.
https://monora.github.io/rgl/
Other
415 stars 59 forks source link

Check for a path between two vertices #42

Closed smithtim closed 5 years ago

smithtim commented 5 years ago

Is there a method to check whether a path exists between two vertices?

E.g. graph.path? v1, v2

monora commented 5 years ago

You can use BFS or DFS graph iterator to get the answer:

require 'rgl/adjacency'
require 'rgl/traversal'

module RGL::Graph
  def path?(v1, v2)
     # create BFS Iterarator starting from v1
     it = self.bfs_iterator(v1)
     # Use method any? of Enumerable
     it.any?(v2)
  end
end

dg=RGL::DirectedAdjacencyGraph[1,2 ,2,3 ,2,4, 4,5, 6,4, 1,6]
dg.path?(1,5) 
=> true
dg.path?(5,1)
=> false

Each GraphIterator is a Stream which implements Enumerable:

dg.bfs_iterator.class.ancestors
=> [RGL::BFSIterator, RGL::GraphVisitor, RGL::GraphIterator, RGL::GraphWrapper, Stream, Enumerable, Object, PP::ObjectMixin, Kernel, BasicObject]
monora commented 5 years ago

@smithtim does my answer help you? Can we close the issue?

smithtim commented 5 years ago

That helps, thanks!

If v1 is not in the graph, it throws an exception. This fixes that:

module RGL::Graph
  def path?(v1, v2)
    # avoid exception if v1 is not in the graph
    return false if not self.has_vertex?(v1)
    # create BFS Iterator starting from v1
    it = self.bfs_iterator(v1)
    # Use method any? of Enumerable
    it.any?(v2)
  end
end

I am surprised that path? is not included in RGL::Graph by default. Maybe it could be added?

monora commented 5 years ago

I would not add the method to the basic Graph API, because:

You could add the method in this module extending module Graph. But that would also surprise people violating the POLS.

I would rather add the code either in README or examples.rb. What do you think?

smithtim commented 5 years ago

I would be okay with having it in traversal.rb. Maybe traversal.rb could be renamed path.rb? Or maybe it could go in its own module? Just throwing out some ideas. I do think it should be part of the library, rather than something people have to copy-paste.

monora commented 5 years ago

I think we can put it in an own module path.rb. Would you like to contribute it?

artkirienko commented 5 years ago

Hi @monora, Please check my PRs, I've tried both approaches: simply added info to the README, created a method in path.rb