【问题标题】:How to Convert Adjacency Matrix to Adjacency List in JavaScript?如何在 JavaScript 中将邻接矩阵转换为邻接表?
【发布时间】:2019-03-11 22:07:09
【问题描述】:

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

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

【问题讨论】:

  • 你为什么期望不止一个数组?他们会从哪里来?
  • 为什么你有[0, 4, 5],而不是[0]
  • 拍摄。对不起。为了测试目的,我压缩了一个更大的矩阵和列表,这是一个错字。我期望一个多维数组,一个邻接列表列表。对?因为邻接列表会列出与其相邻的内容,而不是与其相邻的次数,对吧?

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


【解决方案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; }

【讨论】:

  • 我不知道 JavaScript 有这个内置函数。这真的很酷。非常感谢你。我将查看 .map 和 .filter 的文档以更好地理解这一点。
  • 出于好奇,这是否会是 O(n^2) 的渐近复杂度,因为 .filter 嵌套在 .map 中?
【解决方案2】:

不使用'map'的另一种方法是像下面这样写,这可能不是那么好,但仍然可以完成工作。

function convertToAdjList(adjMatrix) {
  var adjList = [];
  for (var i = 0; i < adjMatrix.length; i++) {
    var array=[];
    for (var j = 0; j < adjMatrix.length; j++) {
      if (adjMatrix[i][j] == 1) {
        array.push(j);
      }
    }
    adjList[i]=array;

  }
   return adjList;
}

可以说时间复杂度是O(V^2)。但是,我想如果我们要将邻接表转换为邻接矩阵,时间复杂度会像 O(V*E)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多