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

标签 javascript multidimensional-array adjacency-matrix adjacency-list converters

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

//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 处加上一个零。有人知道如何解决这个问题吗?

最佳答案

您可以将索引或 -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; }

关于javascript - 如何在 JavaScript 中将邻接矩阵转换为邻接列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55111120/

相关文章:

data-structures - 邻接表和邻接矩阵的区别

javascript - 如何在 Javascript 中生成随机的字母和数字字符串?

javascript - 谷歌地图 API : forcing zoom in to a specific location

ruby - 添加具有主数组的所有数组,不重复

PHP:多维数组元素的串联

python - 从元组列表生成邻接矩阵的更优雅的方法

python - 为大 id 数创建邻接矩阵

javascript - 如何在 Angular2 中使用 jquery 和其他 .js 库

javascript - Angular 2 - 属性指令语法错误..我错过了什么吗?

javascript - 在Javascript中获取多维数组中元素的坐标