如何在JavaScript中将邻接矩阵转换为邻接列表?

问题描述 投票:1回答:1

我正在尝试实现一种方法,将邻接矩阵转换为邻接列表。我的实现没有正确地从矩阵转换为列表。这是我第一次尝试,

//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];

输出只是我期望输出代码的4个数组中的一个,加上索引0处的零。是否有人知道如何解决这个问题?

javascript multidimensional-array adjacency-matrix adjacency-list converters
1个回答
1
投票

您可以将索引或-1映射为不需要的值,然后过滤此值。

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; }
© www.soinside.com 2019 - 2024. All rights reserved.