我有一个图表,我想找到可从节点'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'
如您所见,节点突出显示是正确的。但是,某些边缘不会显示为红色,例如连接O1-S4
和S1-O3
。如何显示所有边缘?
答案 0 :(得分:2)
我可以使用'edgetonew'
的dfsearch
选项并将调用修改为highlight
,以便显示缺少的边缘,如下所示:
v = dfsearch(G, 'O1', 'edgetonew');
h = plot(G);
highlight(h, v(:, 1), v(:, 2), 'nodeColor', 'r', 'edgeColor', 'r');
请注意,O1
到S4
的直接路径未突出显示,但通过S1
和O2
的间接路径是。如果您希望突出显示直接路径,可以使用bfsearch
进行广度优先搜索而不是深度优先搜索:
v = bfsearch(G, 'O1', 'edgetonew');
h = plot(G);
highlight(h, v(:, 1), v(:, 2), 'nodeColor', 'r', 'edgeColor', 'r');