ユーザー定義のノード数 'n' を持つ加重グラフがあります。グラフ内の 2 つの一意のノードを指定すると、2 つのノードを接続するすべてのパスを表示するコードが必要です。 グラフの例
wt=zeros(n,n);
while(1)
i=input('enter the starting node:(0 to quit):');
if (i==0)
break;
end
j=input('enter the destination node:');
wt(i,j)=input('Enter the cost: ');
end
disp('Adjacency Matrix');
for i=1:n
fprintf(' %d',i);
end
for i=1:n
fprintf('\n%d ',i);
for j=1:n
fprintf('%d ',wt(i,j));
end
end
Adjacency Matrix
1 2 3 4 5
1 0 1 1 0 0
2 0 0 0 0 0
3 1 0 0 1 0
4 0 0 1 0 0
5 0 0 0 0 0
行列 wt は、任意の 2 つのノード間の接続を示します。これは、ノード (1,2) (1,3) (3,4) (4,3) が接続されていることを意味します。
fprintf('\nEnter the source');
s=input(':');
fprintf('\nEnter the destination');
de=input(':');
for i=1:n
m=s;
if(m~=i)
for j=i:n
if(m~=j)
if(M(m,j)>0)
p(i,j)=j;
m=j;
end
end
if(p(i,j)==de)
d(i)=1;
break;
end
end
if(d(i)~=1)
for k=1:j
p(i,k)=0;
end
m=s;
for k=n : -1 : i
if(M(m,k)>0)
p(i,n-k+2)=k;
m=k;
end
if(p(i,n-k+2)==de)
d(i)=1;
break;
end
end
end
end
end
for i=1:n
j=1;
if(d(i)==1)
for j=1:n
if (j==1)
fprintf('\n path: %d',s);
kk=s;
elseif (p(i,j)>0)
fprintf('->%d',p(i,j));
plot([nodes(kk, 2) nodes(p(i,j), 2)], [nodes(kk, 3) nodes(p(i,j), 3)], 'k.--')
kk=p(i,j);
end
end
end
fprintf('\t\t hopcount of path %d: %d',i,count);
count=0;
end
これは、ソースから宛先への可能なパスを見つけるために私が書いたコードです。'p' 行列は、ソースから宛先への最終的なパスを保持します。出力:
enter the starting node:(0 to quit):1
enter the destination node:2
Enter the cost: 1
enter the starting node:(0 to quit):1
enter the destination node:3
Enter the cost: 1
enter the starting node:(0 to quit):2
enter the destination node:3
Enter the cost: 1
enter the starting node:(0 to quit):0
Enter the source:1
Enter the destination:3
hopcount of path 1: 0
path 2: 1->2->3 hopcount of path 2: 2
path 3: 1->3 hopcount of path 3: 1???
Attempt to reference field of non-structure array.
ソースに 3、宛先に 1 を入力すると、コードが機能しません。