gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:07:23 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com