你能告诉我为什么这个MATLAB代码是错误的吗?我不明白为什么。事先非常感谢。
function [mst, cost] = prim(A)
[n,n] = size(A);
A, n, pause,
if norm(A-A','fro') ~= 0 ,
disp(' Error: Adjacency matrix must be symmetric ')
return,
end;
intree = [1]; number_in_tree = 1;
number_of_edges = 0;
notintree = [2:n]'; number_notin_tree= n-1;
in = intree(1:number_in_tree),
out = notintree(1:number_notin_tree),
pause,
while number_in_tree < n,
mincost = Inf;
for i=1:number_in_tree,
for j=1:number_notin_tree,
ii = intree(i); jj =
notintree(j);
if A(ii,jj) < mincost,
mincost = A(ii,jj); jsave = j;
iisave = ii; jjsave = jj;
end;
end;
end;
number_of_edges = number_of_edges +1;
mst(number_of_edges,1) = iisave;
mst(number_of_edges,2) = jjsave;
costs(number_of_edges,1) = mincost;
number_in_tree = number_in_tree + 1;
intree = [intree; jjsave];
for j=jsave+1:number_notin_tree,
notintree(j-1) = notintree(j);
end;
number_notin_tree = number_notin_tree - 1;
in = intree(1:number_in_tree),
out = notintree(1:number_notin_tree),
pause,
end;
disp(' Edges in minimum spanning tree and their costs: ')
[mst costs]
cost = sum(costs)
当我点击运行按钮说:
Not enough input arguments.
Error in prim (line 10)
[n,n] = size(A);
% The matrix is n by n, where n = # nodes.
然而,当我用调用命令窗口中的函数时
s=[1 1 2 2 2 3 3 4 4 4 5 5 6 7];
t=[2 3 4 5 3 5 6 5 7 8 6 8 7 8];
w=[3 5 4 7 4 9 8 3 11 8 3 9 8 7];
G = graph(s,t,w);
A = adjacency(G);
prim(A)
代码工作"正确">
作为最终答案返回
mst=
cost=
All zero sparse: 1-by-1
它应该返回
mst=
12
2 3
2 4
4 5
5 6
6 7
7 8
成本=32
为什么不返回?
在运行过程中,程序从1变为4,尽管它本应变为2。然后从4到5,这是正确的,但我不知道为什么跳过2和3,直接进入4、5、6、7、8。
请帮帮我。
如果您知道有其他代码,请提供,也许更简单。
函数的主要问题是,当您检查当前边的成本是否低于mincost
时,您没有验证那里是否真的有边。如果没有优势,那么成本将是0
,这自然低于任何正成本值。您需要更改线路:
if A(ii,jj) < mincost,
至
if (A(ii,jj) > 0) && (A(ii,jj) < mincost), % A(ii,jj) is edge and lower cost than mincost
用作输入的相邻矩阵:
A =
0 3 5 0 0 0 0 0
3 0 4 4 7 0 0 0
5 4 0 0 9 8 0 0
0 4 0 0 3 0 11 8
0 7 9 3 0 3 0 9
0 0 8 0 3 0 8 0
0 0 0 11 0 8 0 7
0 0 0 8 9 0 7 0
此更改后的输出为:
mst =
1 2
2 3
2 4
4 5
5 6
4 8
8 7
cost = 32