1

Suppose there are n distinct points P1, P2,...,Pn.

Define the connectedness matrix M=(c_ij) to be a square matrix of the size n.c_ij will give true if i=j or there is a line segment between point Pi and Pj.

A set of points are connected if between any two points there is at least one path(set of line segments). We call the connected set of point a proper graph. A point itself can be a proper graph.

Two proper graphs are disconnected when there is no connection from any point in the first graph to any point in the second graph.

Connectedness is defined as number of disconnected proper graphs.

For example,

       P1    P2    P3    P4    P5
 P1   true  false true  false false
 P2   false true  false false false
 P3   true  false true  false true
 P4   false false false true  true
 P5   false false true  true  true

has two disconnected proper graphs, i.e. P2 and {P1,P3,P4,P5}.

My problem is how to write a function to takes in the connectedness matrix and return a list of disconnected proper graphs. For example, the above example should return list(list(1,3,4,5),list(2)).

user122049
  • 397
  • 1
  • 11

1 Answers1

0

You are looking for the connected components of the graph.

Unfortunately, an adjacency matrix like this is quite sub-optimal because you cannot get faster than O(n^2). In the following, I describe two solutions that you can use. The first one is better when you have direct access to neighbors, the second one is better if you have direct access to edges. None of that applies to your scenario. The time complexities for both solutions is equal for an adjacency matrix. So you would have to measure, which one is actually faster.

If you have a data structure that lets you access the neighbors directly, you can use BFS or DFS to get the connected components. The method is described in this answer. Note that the time complexity stated in this answer does not apply to your scenario.

For cases where you have access to the edges, you can use the union-find data structure. You can then do the following:

Initialize union-find uf with n entries
for every edge (i, j)
    uf.union(i, j)
next
initialize map int -> list of vertices
for every vertex v
    p <- uf.representative(v)
    map[p].insert(v)
next

The lists in the map are then the connected components.

Community
  • 1
  • 1
Nico Schertler
  • 32,049
  • 4
  • 39
  • 70