【发布时间】: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