Sie sind auf Seite 1von 3

% first of all we clear all data from matlab memory and clear screen

clc
clear all
close all
fprintf('\n MATLAB PROGRAMMING WELCOMES YOU \n This programm is for
Shortest Path by Bellman-Ford method \n');
% Un-Directed Graph
%%Bellman-Ford method%%
tn = input(' \n Enter total number of Node \n ');% total no of node
m = zeros(tn,tn);
char y ;
char n;
fprintf('We are assuming un-directed Graph method that means our path value
matrix will be symmetric \n \n ');
for i=1:tn
for j=i+1:tn % matrix will be symmitric
if i==j
m(i,j)=0;
else
fprintf('If Node %d and %d connected than enter Y otherwise N
\n',i,j);
chr_check = input('','s');
check = strcmpi(chr_check,'Y'); % compare character
if (check==1)
fprintf('Enter Path value for Node %d and %d \n',i,j);
m(i,j)=input('');
m(j,i)=m(i,j);
else
fprintf('means you are saying that Node %d and %d are not
connected \n\n',i,j);
m(i,j)=0;
m(j,i)=0;
end

end
end
fprintf('\n \n');
end
tt=1;


while(tt>=1)

if tt~=1
fprintf('\n If you Want to Change your path Value Matrix than Enter 1
otherwise 0 \n');
checkk = input('');
if checkk == 1
fprintf('\nNow you have changed your Path Value Matrix \n');
m=randi([1,10],tn); %nowgive any random value to change path
matrix
for i=1:tn
m(i,i)=0;
end
elseif checkk==0
break;
end
end

tt=tt+1;




k=1;
% define Edge number = [first node][second node]
for i=1:tn
for j=1:tn
if m(i,j) ~= 0 % if edge not exit than skip that path
edge(k,1) = i ;
edge(k,2) = j;
k=k+1;
end
end

end

% first we initilize that shortest of all node is infinity i.e. 999 except 1
for that value is zero
d(1)=0;
for i=2:tn
d(i)=999;
end


% now we run loop and using Bellman -Ford method
% now we do relaxtation for each Edge
% total no of Edges are = k-1
for i=1:tn
for j=1:k -1 % run loop for each path
if (d(edge(j,2)) > d(edge(j,1))+m(edge(j,1),(edge(j,2)))) % if earlier
value is greater than change it

d(edge(j,2)) = d(edge(j,1))+m(edge(j,1),(edge(j,2)));
lastlabel(edge(j,2)) =edge(j,1);

end
end

end

% printing shortest path
fprintf(' \n Shortest path values are from Node 1 ( Origin) \n
Label(Destination) = [Total path value, Predessor Node]\n')

for i=1:tn
fprintf(' Label( %d ) = [ %d , %d ] \n ',i,lastlabel(i),d(i));
end
fprintf('\n You are running your Code %d time \n',tt-1);
%blog information
fprintf('\n \nThanks For using this Programme\n :- Vijay Singh Kulhar \n\n
For more programme you can visit my blog @ http://kulharvijay.wordpress.com/
');

end

Das könnte Ihnen auch gefallen