我有一个如下的MATLAB矩阵:
column no: 1 2 3 4 5 6
matrix elements 1 1 2 3 6 2
列号表示节点ID,矩阵元素表示该节点指向的节点。请帮助我找到从特定节点到节点1的跳数。我编写了以下代码,但不能解决问题。
x = ones(1, n);
checkbit = zeros(1, n);
nodedest = [1 1 2 3 6 2];
hopcount = zeros(1, n);
for i = 1:n
for j = 1:n
if nodedest(j) == 1 && checkbit(j) == 0
hopcount(j) = hopcount(j) + 1;
checkbit(j) = 1;
else
x(j) = nodedest(j);
end
if x(j) ~= 1
hopcount(j) = hopcount(j) + 1;
x(j) = nodedest(x(j));
end
end
end
答案 0 :(得分:0)
您正在寻找breadth-first search来在图形中找到shortest path。给定图的树状结构,无需任何方式接触数据,就可以在每个节点的O(n)时间内完成此操作:
nodedest = [1 1 2 3 6 2];
hopcount = zeros(1, 6);
for n = 2:6
k = n
while k ~= 1
hopcount(n) = hopcount(n) + 1
k = nodedest(k)
end
end
如果您愿意反转边缘感(引入一对多关系),则可以一次性完成同一件事,从而将整个算法从O(n 2 )到O(n)的时间复杂度。权衡是内存复杂度将从O(1)增加到O(n):
nodedest = [1 1 2 3 6 2];
% Reverse the input
nodesource = cell(1, 6);
nodesource(:) = {[]}
for n = 2:6
k = nodedest(n);
nodesource{k} = [nodesource{k} n];
end
% implement bfs, using the assumption that the graph is a simple tree
hopcount = zeros(1, 6);
cache = [1];
hops = 0;
while ~isempty(cache)
next = []
for c = cache
hopcount(c) = hops;
next = [next nodesource(c)]
end
hops = hops + 1;
cache = next
end