0

I want to create an adjacence matrix given n lines that represent a partial connection between some nodes of a graph. For example, due to the fact that each line represent a clique, the lines A-B; B-C; C-D; A-E-D form the following graph.

resulting graph

My first approach was using a for loop to read each line, for each line I use another for loop to obtain each node in it, finally, with another for loop I check if the rest of the nodes are already in the adyacence list of the node analized, if not, I add it. All of this gives a O(n^3) complexity. Is there another way for making this task with a lower complexity? Is it possible to complete this with O(n)?

Jorge
  • 75
  • 1
  • 10

1 Answers1

0

In pseudo code, you can do something like this:

A[n,n] <- {0 ... 0n}    // Dense matrix size n x n , initalized to zero.

for L in LINES:          // Loop through input lines
  {N,adj}=Split(L)       // Split Node and adjecencies
  I=IDNameToIndex(N)  // Numeric index corresponding to Node name or id.
  for n in adj:          // Loop through adjecencies 
     i=IDNameToIndex(n)  // Numeric index corresponding to Node name or id.
     A[I,i]=1;           // Set unidrectional adjecency 
     A[i,I]=1;           // Set bidirectional adjecency(optional, depending on input)
visibleman
  • 3,175
  • 1
  • 14
  • 27