Search code examples
prologgraph-theoryconnected-components

Getting connected components of graph in Prolog


I'm struggling with logic programming. I have a this problem and I hope some of you can help me with it. Discontinous graph is represented by facts in this way:

h(0,1).
h(1,2).
h(3,4).
h(3,5).

So there is two separate graph components. I would like all the separate components on the output represented by a list. So if there is three separate components in the graph, there will be three lists. For the given example above, the expected output is [[0,1,2],[3,4,5]].


Solution

  • Using iwhen/2 we can define binrel_connected/2 like so:

    :- use_module(library(ugraphs)).
    :- use_module(library(lists)).
    
    binrel_connected(R_2, CCs) :-
       findall(X-Y, call(R_2,X,Y), Es),
       iwhen(ground(Es), ( vertices_edges_to_ugraph([],Es,G0),
                           reduce(G0,G),
                           keys_and_values(G,CCs,_) )).
    

    Sample query on SICStus Prolog 4.5.0 with symm/2 for symmetric closure:

    | ?- binrel_connected(symm(h), CCs).
    CCs = [[0,1,2],[3,4,5]] ? ;
    no