I need to make a predicate isConnected/1 that takes a graph as an argument and determines if there is an undirected path between the pairs.
Suppose I have a list of edges (where G is a graph):
isEdge(G,1,2).
isEdge(G,2,3).
isEdge(G,4,5).
So because there is no edge between 3 and 4 this should fail.
How would I approach this problem? Would I have to traverse though each edge and record the edges in a list? or is there a better approach to do this?
Solution 1: Using a library
This is easy once you use a graph theory library. I'll first rewrite your graph using S-representation:
Then I'll use library
ugraphincluded in SWI-Prolog (thanks to Richard O'Keefe and Vitor Santos Costa):Solution 2: "Do it yourself"
Instead of relying on existing libraries, you can also implement this yourself in various ways (much recommended if you want to become a better programmer!). One way to implement this form the ground up is to use closure0/3 which implements reflexive-transitive closure over a binary predicate (created by SO user false).
If you add the appropriate edges to your database:
... you can now query: