%%%%%%%%%%%%%%%%%%%%%%%% % Breadth-First Search % %%%%%%%%%%%%%%%%%%%%%%%% %% 'dist' gives shortest distance in terms of # arcs. %% dist is initialized to infinity for all nodes. %% Then dist(s) is set to zero. Then, as we increase %% breadth of the search by one level, the distance %% of the nodes marked in the current level is set to %% dist(i) + 1, where i is the node from which the new %% nodes in the current level are accessed from. %% Rather than adding nodes to and deleting nodes from LIST, %% we use two variables first and last to keep track ot it. % s---starting node for BFS Search s = input('give the starting node for the BFS search '); LIST=[s]; first=1; last=length(LIST); mark=zeros(1,N); mark(s)=1; pred=zeros(1,N); bigM = 10000; %% acts like infinity dist=bigM*ones(1,N); dist(s)=0; while first <= last i=LIST(first); if ~isempty(A{i}) jj=H(A{i}); %A{i} stores arc_names admit=jj( find( mark(jj)==0 ) ); mark(admit)=1; pred(admit)=i; dist(admit) = dist(i) + 1; LIST=[LIST admit']; last=last+length(admit); end%if first=first+1; end%while dist BFS=LIST; fprintf(1,'\nBFS visits nodes 1 to %d in the sequence ',N); fprintf(1, ' %d ',BFS); fprintf(1,'\n\n'); order=zeros(1,N); order(BFS)=(1:length(BFS)) pred