Algorithm for determining equivalence classes

Rather, a general question. I have a list like this:

A B  
A C  
C A   
D E  
F G   
E F  
C L  
M N  

etc.

What I want to do is figure out all the relationships and put everything that is connected on one line. Example above:

A B C L   
D E F G  
M N      

so that each letter appears only once, and the letters associated with each other are included in one line (list, array, whatever).

Is this some kind of known problem with a well-defined algorithm? Does he have a name? It seems like it should be. I would suggest that some kind of recursive solution should be in place.

+4
source share
2 answers

- G = (V, E). E, - G. Python, NetworkX.

Demo

>>> data
[['A', 'B'], ['A', 'C'], ['C', 'A'], ['D', 'E'], ['F', 'G'], ['E', 'F'], ['C', 'L'], ['M', 'N']]
>>> import networkx as nx
>>> G = nx.Graph()
>>> G.add_edges_from( data )
>>> components = nx.connected_components( G )
>>> print "\n".join([ " ".join(sorted(cc)) for cc in components ])
A B C L
D E F G
M N
+5

https://en.wikipedia.org/wiki/Connected_component_(graph_theory)

( , , , .)

a Node, - . , .

:

Map<Node, Component> map.

:

For each edge E:
    For each node N in E (i.e. all two of them):
        Component c = map.get (N)
        if c doesn't exist then:
            c = new Component
            map.put (N, c)

        c.add (N)

For each Component C in map.values ():
    Print (sort C nodes)
+2

Source: https://habr.com/ru/post/1530630/


All Articles