我有一个包含四个 column1 Linknumbers 的矩阵(现在不重要), column2:start,column3:end 和 column4 如果大于 0 -> 则节点已连接。我写了一个递归代码,但它没有正确显示输出:例如:在节点 1 和 18 之间它输出
path=[1 2 6 8 16 18] % which is correct
path=[1 2 6 8 16 7 18] % from 8 there are two paths (16 and 7)- it shouldnt show 16 anymore
% the code is
function findpaths(Matrix,start, destination,pathD)
if(start==destination)
pathD % have a problem in storing them too (it just outputs now)
return
end
% to find all the rows that have start
% then it can find all the nodes connected to start
% if start is 6 then it return 4 and 9th row where
%there are 8 and 5 connected to 6 in those rows
[row] = find(Matrix(:,2)==start); % to find all the rows that have this node
for i=1:size(row,1) % adjecent nodes to start
if Matrix(row(i),4)>0 % condition to see if the nodes are connected
adj_node = Matrix(row(i),3); % the adjacent node
if ismember(adj_node, pathD)==0
pathD;
pathD = [pathD adj_node];
start = adj_node;
findpaths(Matrix,start,destination,pathD);
end
end
end
end
下面是矩阵
1 1 2 1
2 1 3 0
4 2 6 1
16 6 8 1
6 3 4 0
7 3 12 0
21 8 9 0
10 4 11 0
15 6 5 0
22 8 16 0.5
20 8 7 0.5
37 12 13 0
32 11 10 0
25 9 10 0
49 16 17 0
18 7 18 0.5
28 10 15 0
50 16 18 0.5
34 11 14 0
53 17 19 0
39 13 24 0
46 15 22 0
56 18 20 0
42 14 23 0
76 24 23 0
62 20 21 0
69 22 21 0