Search code examples
javascriptmultidimensional-arrayadjacency-matrixadjacency-listconverters

How to Convert Adjacency Matrix to Adjacency List in JavaScript?


I am trying to implement a method to convert an adjacency matrix into an adjacency list. My implementation does not correctly convert from a matrix into a list. This was my first attempt at it,

//Adjacency Matrix to Adjc list

function convertToAdjList(adjMatrix) {
  var adjList = new Array(adjMatrix.length - 1);

  for (var i = 0; i < adjMatrix.length; i++) {
    if (adjMatrix[i] == 1) {
      //I think i have to do something here.
    }
    for (var j = 0; j < adjMatrix.length - 1; j++) {
      if (adjMatrix[i][j] == 1) {
        adjList[i] = i;//not sure if this is quite right.
      }
    }
  }
  return adjList;
}
var testMatrix = [
  [0, 1, 1, 1],
  [1, 0, 0, 0],
  [1, 0, 0, 0],
  [1, 0, 0, 0]
];
console.log(convertToAdjList(testMatrix)); //[[1,2,3],[0],[0],[0];

The output is just one of the 4 arrays i expected the code to output, plus a zero at index 0. Does anyone have an idea on how to fix that?


Solution

  • You could map the indices or -1 as unwanted value and then filter this value.

    function convertToAdjList(adjMatrix) {
        return adjMatrix.map(a => a.map((v, i) => v ? i : -1).filter(v => v !== -1))
    }
    
    var testMatrix = [ [0, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]];
    
    console.log(convertToAdjList(testMatrix)); // [[1, 2, 3], [0], [0], [0]]
    .as-console-wrapper { max-height: 100% !important; top: 0; }