Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/88.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JavaScript中将邻接矩阵转换为邻接列表?_Javascript_Multidimensional Array_Adjacency Matrix_Adjacency List_Converters - Fatal编程技术网

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

如何在JavaScript中将邻接矩阵转换为邻接列表?,javascript,multidimensional-array,adjacency-matrix,adjacency-list,converters,Javascript,Multidimensional Array,Adjacency Matrix,Adjacency List,Converters,我正在尝试实现一种将邻接矩阵转换为邻接列表的方法。我的实现没有正确地将矩阵转换为列表。 这是我第一次尝试 //邻接矩阵到邻接列表 函数convertToAdjList(adjMatrix){ var adjList=新数组(adjMatrix.length-1); 对于(var i=0;iv?i:-1).filter(v=>v!=-1)) } VarTestMatrix=[[0,1,1,1]、[1,0,0,0]、[1,0,0,0]、[1,0,0]; log(convertToAdjList(t

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

//邻接矩阵到邻接列表
函数convertToAdjList(adjMatrix){
var adjList=新数组(adjMatrix.length-1);
对于(var i=0;ilog(convertToAdjList(testMatrix))//[[1,2,3]、[0]、[0]、[0];
您可以将索引或
-1
映射为不需要的值,然后过滤此值

函数转换为调整列表(调整矩阵){
返回adjMatrix.map(a=>a.map((v,i)=>v?i:-1).filter(v=>v!=-1))
}
VarTestMatrix=[[0,1,1,1]、[1,0,0,0]、[1,0,0,0]、[1,0,0];
log(convertToAdjList(testMatrix));//[[1,2,3],[0],[0],[0]].

.as console wrapper{max height:100%!important;top:0;}
不使用“map”的另一种方法是像下面这样编写,这可能不是很好,但仍然可以完成工作

函数转换为调整列表(调整矩阵){
var adjList=[];
对于(var i=0;i}
为什么需要多个数组?它们来自哪里?为什么要使用
[0,4,5],
而不是
[0]
?糟了。抱歉。为了测试的目的,我压缩了一个更大的矩阵和列表,这是一个打字错误。我希望有一个多维数组,一个邻接列表。对吗?因为邻接列表将列出与其相邻的内容,而不仅仅是某个内容与之相邻的次数,对吗?我不知道JavaScript将其作为bui在函数中。这真的很酷。非常感谢。我将查看.map和.filter的文档以更好地理解这一点。出于好奇,这是否是O(n^2)的渐进复杂性,因为.filter嵌套在.map中?