如何解决图论Matlab BFS算法
我正在尝试编写一个将邻接矩阵转换为BFS列表的函数。输出包含两行,第一行是节点的索引,第二行是访问节点的顺序。 该函数应如下所示,其中A是邻接矩阵:
功能[森林] = Find_BFS_forest(A)
例如, 当输入A为[0,1,0; 1,0; 0,0, 0,0; 1,0] edge_list是{(1,2)(1,5)(2,3)}。我希望输出为[1,2,5,3,4,6; 0,0]
n=length(A);
% vis to mark if a node is visited earlier or not
vis=zeros(n,1);
% pred to predecessor of each node
pred=zeros(n,1);
% path to store the bfs traversal
path =zeros(n,1); pp = 1;
for i = 1:n
% start bfs from each unvisited node i
if vis(i) == 0
% search queue and search queue tail/head
sq=zeros(n,1);
sqt=1;
sqh=0;
% push starting node in the queue
sq(sqt)=i;
while sqt-sqh>0
% pop v off the head of the queue
sqh=sqh+1;
v=sq(sqh);
path(pp) = v;
pp=pp+1;
for u=1:n
if A(v,u)==1 && vis(u)==0
% if u is connected to v and is unvisited push it to the queue
sqt=sqt+1;
sq(sqt)=u;
vis(u) = 1;
pred(u)= v;
end
end
end
end
end
% create the output forest
forest = zeros(2,n);
for i=1:n
forest(1,i) = path(i);
forest(2,i) = pred(path(i));
end
end
这是我现在拥有的代码,但是节点在重复。我应该在哪里进行更改?
谢谢!
解决方法
您忘记将每棵树的初始节点标记为visited
:
for i = 1:n
% start bfs from each unvisited node i
if vis(i) == 0
vis(i) = 1; % mark initial node as visited <-- added
% search queue and search queue tail/head
...
加法后的输出:
forest =
1 2 5 3 4 6
0 1 1 2 0 0
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。