我有以下代码用两种类型的节点“S”和“O”生成大小(i,j)的图形。所有节点都存储在单元阵列nodeNames
i=input('i:');
j=input('j:');
B=randi([0 1], i*2,j);
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);
现在我使用dfssearch
函数来获取节点O1的所有路径,例如:
v = dfsearch(G,'O1');
结果是从“O”和“S”类型的O1可到达的所有节点的树。
我想做以下事情;得到一个树重组“O”型节点的所有路径;例如:如果我dfsearch(G,'O1')
,在找到另一个类型为'O'的节点(例如O2)的那一刻,我为找到的节点(O2)dfsearch(G,'O2')
调用dfssearch,并且我重复以下内容,直到找到所有节点。如果节点已经处理过,我不这样做。这有什么办法吗?
谢谢。
答案 0 :(得分:3)
诀窍是使用一个虚拟起始节点来扩充图形,该节点具有每个O
节点的边缘。然后,您可以从新的虚拟节点开始搜索,并且将继续搜索之前未访问过的所有O
个节点。
...
% 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)')))];
% Add new node called 'X' that will be the starting node
nodeNames{end+1} = 'X'
...
现在您已经处理了节点名称,将新节点添加到邻接矩阵中:
...
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
adj(end+1,end+1) = 0; % add 1 row and 1 column to adj
adj(end, 1:nNodeCol) = 1; % only outgoing edges from X to O*
...
从这里你可以创建有向图并运行dfsearch
:
v = dfsearch(G,'X');
生成的顶点列表将从X
开始(可轻松删除)并包含所有O
个节点。
注意:每个代码块的第一行与原始代码相同,只是为了给你一个关于新代码放置位置的参考点。