最近遇到一个问题,在已知路径节点坐标和路径节点间联通关系的情况下,遍历出指定起点和终点间的所有路径。需要用MATLAB实现,本着能COPY绝不自己写的原则,网上搜索的很多,果然没有现成的,既然这样那就只能自己手撕了。
虽然没有找到可以copy的资源,但是也搜索到了比较有用的信息——这类问题一般就是用深度优先搜索来处理(详细原理不在赘述)。写了个测试代码,测试效果还可以,供有需要的友人参考,欢迎交流,要是有更好的实现方式欢迎科普。
clc
clear
global loc G flag st ed stack rec id
loc=[1 9
-1 7
3 7
-2 5
0 5
2 6
4 6
-1 3];%节点坐标
G=[0 1 1 0 0 0 0 0
1 0 0 1 1 0 0 0
1 0 0 0 0 1 1 0
0 1 0 0 0 0 0 1
0 1 0 0 0 0 0 1
0 0 1 0 0 0 1 0
0 0 1 0 0 1 0 0
0 0 0 1 1 0 0 0];%邻接矩阵
flag=zeros(1,size(G,1));%访问标记
st=4;%开始点
ed=7;%结束点
flag(st)=1;
stack=st;
rec=[];
id=0;
dfs();%深度优先搜索
rec
figs=1;
figure(figs)
for i=1:size(G,1)
for j=1:size(G,2)
if G(i,j)==1
plot([loc(i,1) loc(j,1)],[loc(i,2) loc(j,2)],'r-','LineWidth',1.5);
hold on
end
end
text(loc(i,1)+0.15,loc(i,2)+0.15,num2str(i));
hold on
plot(loc(i,1),loc(i,2),'o','MarkerSize',15,'MarkerEdgeColor','b','MarkerFaceColor','r');
end
title('路网图')
xlabel('x')
ylabel('y')
for i=1:length(rec)
temp=rec{i};
figs=figs+1;
draw(figs,i,temp);
end
function []=dfs()
global G flag st ed stack rec id
if st==ed
id=id+1;
rec{id}=stack;
flag(stack(end))=0;
stack=stack(1:end-1);
st=stack(end);
return;
else
% cnt=0;
for i=1:size(G,1)
if(G(st,i)==1 && flag(i)==0)
temp=[stack i];
tempn=length(temp);
isrepeat=0;
if ~isempty(rec)
for j=1:length(rec)
if length(rec{j})>=tempn && sum(abs(rec{j}(1:tempn)-temp))==0
isrepeat=1;
break;
end
end
end
if isrepeat==1
continue;
end
% cnt=cnt+1;
stack=[stack i];
flag(i)=1;
st=i;
dfs();
end
end
if length(stack)>1
flag(stack(end))=0;
stack=stack(1:end-1);
st=stack(end);
else
return;
end
end
end
function []=draw(figs,idx,rt)
global loc G
figure(figs)
for i=1:size(G,1)
for j=1:size(G,2)
if G(i,j)==1
plot([loc(i,1) loc(j,1)],[loc(i,2) loc(j,2)],'r-','LineWidth',1.5);
hold on
end
end
if i==rt(1)
text(loc(i,1)+0.15,loc(i,2)+0.15,'start');
hold on
plot(loc(i,1),loc(i,2),'o','MarkerSize',20,'MarkerEdgeColor','b','MarkerFaceColor','g');
hold on
elseif i==rt(end)
text(loc(i,1)+0.15,loc(i,2)+0.15,'end');
hold on
plot(loc(i,1),loc(i,2),'o','MarkerSize',20,'MarkerEdgeColor','b','MarkerFaceColor','g');
hold on
else
text(loc(i,1)+0.15,loc(i,2)+0.15,num2str(i));
hold on
plot(loc(i,1),loc(i,2),'o','MarkerSize',15,'MarkerEdgeColor','b','MarkerFaceColor','r');
hold on
end
end
for j=1:length(rt)-1
plot([loc(rt(j),1) loc(rt(j+1),1)],[loc(rt(j),2) loc(rt(j+1),2)],'g-','LineWidth',2);
hold on
end
title(['路径图',num2str(idx)])
xlabel('x')
ylabel('y')
end
结果展示: