gpt4 book ai didi

javascript - 找到目标的目标,即强制定向图中 friend 的 friend

转载 作者:行者123 更新时间:2023-11-29 10:43:54 25 4
gpt4 key购买 nike

我正在使用 D3.JS 库强制定向图,

我正在使用以下代码来查找目标节点

graph.links.forEach(function(d) {
linkedByIndex[d.source.index + "," + d.target.index] = 1;
linkedByIndex[d.target.index + "," + d.source.index] = 1;
});
});


function neighboring(a, b) {
return a.index == b.index || linkedByIndex[a.index + "," + b.index];
}

如何找到并突出显示目标的目标?有人可以帮我解决这个问题吗?

编辑:

通过以下方式解决了问题:

先创建邻接矩阵:

var adjMat=null;
var adjMatSq=null;


adjMat=new Array(graph.nodes.length);
for(var i = 0;i < graph.nodes.length; ++i)
{
adjMat[i]=new Array(graph.nodes.length);
for(var j = 0; j < graph.nodes.length; ++j)
{
adjMat[i][j] = 0;
}
}

然后将值赋值给相邻的矩阵:

graph.links.forEach(function(d) {
adjMat[d.source.index][d.target.index] = adjMat[d.target.index][d.source.index] = 1;
adjMat[d.source.index][d.source.index] = 1;
});

adjMatSq=matrixMultiply(adjMat, adjMat);
});

然后我找到了矩阵的平方,这样我就可以得到二阶节点:

function matrixMultiply(m1,m2)
{
var result = [];
for(var j = 0; j < m2.length; j++) {
result[j] = [];
for(var k = 0; k < m1[0].length; k++) {
var sum = 0;
for(var i = 0; i < m1.length; i++) {
sum += m1[i][k] * m2[j][i];
}
result[j].push(sum);
}
}
return result;
}

定义了一个函数来查找二阶节点:

    function areAtSecondDegree(a,c)
{
return adjMatSq[a.index][c.index] == 1;
}

My Code Plnkr

最佳答案

原理如下。给定一个特定的节点,确定它的直接邻居。要获得二级邻居,请使用您刚刚确定的邻居列表,并为每个邻居再次获取邻居列表。所有这些列表的联合是一级和二级邻居的列表。

在代码中这可能是这样的:

var connected = {};
var friends = graph.nodes.filter(function(o) { return areFriends(d, o); });
friends.forEach(function(o) {
connected[o.name] = 1;
// second pass to get second-degree neighbours
graph.nodes.forEach(function(p) {
if(areFriends(o, p)) {
connected[p.name] = 1;
}
});
});

如果您想拥有任意 n 度邻居,则需要更改此设置以适应您不知道要运行多少次迭代的事实。

完整演示 here .

关于javascript - 找到目标的目标,即强制定向图中 friend 的 friend ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23386277/

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