找到最小的生成树

时间:2018-12-01 06:09:59

标签: matlab tree mathematical-optimization discrete-mathematics minimum-spanning-tree

能否请您告诉我为什么此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 =

     

1 2

     

2 3

     

2 4

     

4 5

     

5 6

     

6 7

     

7 8

     

costs = 32


为什么没有退还?

虽然运行程序应该从1转到4,但是应该从4转到5,这是正确的,但是我不知道为什么跳过2和3并直接转到4,5,6, 7,8。

请帮助我。


如果您知道其他代码,请提供,可能更简单。

1 个答案:

答案 0 :(得分:1)

该函数的主要问题是,当您检查当前边的成本是否低于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