matlab - 图论 Matlab BFS 算法
问题描述
我正在尝试编写一个将邻接矩阵转换为 BFS 列表的函数。输出包含两行,一是节点的索引,二是访问节点的顺序。该函数应如下所示,其中 A 是邻接矩阵:
函数 [ 森林 ] = Find_BFS_forest( 一 )
例如,当输入 A 为 [0,1,0,0,1,0;1,0,1,0,0,0;0,1,0,0,0,0;0,0,0 ,0,0,0;1,0,0,0,0,0;0,0,0,0,0,0] edge_list 是 {(1,2) (1,5) (2,3) }。我希望输出为 [1,2,5,3,4,6;0,1,1,2,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
推荐阅读
- python - SQLite3 帮助,将变量保存到数据库中
- android-studio - 使用 Android Studio 将 Flutter 项目上传到 Github
- c++ - std::memcpy vs std::copy_n 用于遗留 c 结构
- wordpress - 如何禁用 TLS 1.0 和 1.1 以在 Apache 中为 Wordpress Bitnami Amazon-Ligthsail 实例仅启用 TLS 1.2 和 TLS 1.3?
- batch-file - 如何制作自定位批处理文件
- flexbox - 无法让 flexbox 容器水平扩展以匹配内容
- ios - 表格视图不显示单元格
- r - 如何在ggplot中使用axis.text.y在y轴上旋转特定元素/标签?
- ffmpeg - 如何使用较旧的 NVEnc 编译 FFMpeg?
- python - 您如何有条件地将值分配给列?