如何在有向图中突出显示所有所需的路径?

时间:2017-07-12 18:57:47

标签: matlab matrix graph

我有一个图表,我想找到可从节点'O1'访问的所有节点,所以我使用以下内容:

B=[1 1 1 0 ; 0 1 1 0; 0 1 0 1; 0 1 0 1; 0 0 0 0 ; 0 0 1 0; 1 1 1 0; 0 1 0 0];   
nNodeCol = size(B,2);                            % one node for each column of B
nNodeLine = size(B,1)/2;                         % one node for every two lines of B
% First the column nodes, then the line nodes:
nodeNames = [cellstr(strcat('O',num2str((1:size(B,2))'))) ; cellstr(strcat('S',num2str((1:size(B,1)/2)')))];
% Adjacency matrix adj, adj(i,j)=1 means there is an edge from node#i to node#j:
adj = zeros(nNodeCol+nNodeLine);                 % square matrix which size is the number of nodes
adj(1:nNodeCol, nNodeCol+1:end) = B(1:2:end,:)'; % edge from a column node to a line node is added for all the 1 in the first line of the node in the matrix
adj(nNodeCol+1:end, 1:nNodeCol) = B(2:2:end,:);  % edge from the line node to a column node is added for all the 1 in the second line of the node in the matrix
% Creation of the graph:
G = digraph(adj,nodeNames);
h = plot(G); 
v = dfsearch(G,'O1');
highlight(h,v,'nodeColor','r');
highlight(h,v,'edgecolor','r');

单元格数组v包含以下内容:

'O1'
'S1'
'O2'
'S2'
'O4'
'S4'
'O3'

但我的问题是当我绘制结果时,并非显示所有边缘: enter image description here

如您所见,节点突出显示是正确的。但是,某些边缘不会显示为红色,例如连接O1-S4S1-O3。如何显示所有边缘?

1 个答案:

答案 0 :(得分:2)

我可以使用'edgetonew'dfsearch选项并将调用修改为highlight,以便显示缺少的边缘,如下所示:

v = dfsearch(G, 'O1', 'edgetonew');
h = plot(G);
highlight(h, v(:, 1), v(:, 2), 'nodeColor', 'r', 'edgeColor', 'r');

enter image description here

请注意,O1S4的直接路径未突出显示,但通过S1O2的间接路径是。如果您希望突出显示直接路径,可以使用bfsearch进行广度优先搜索而不是深度优先搜索:

v = bfsearch(G, 'O1', 'edgetonew');
h = plot(G);
highlight(h, v(:, 1), v(:, 2), 'nodeColor', 'r', 'edgeColor', 'r');

enter image description here