www.gusucode.com > matlab 案例源码 matlab代码程序 > matlab/BreadthFirstSearchWithMultipleComponentsExample.m
%% Breadth-First Graph Search with Multiple Components % Perform a breadth-first search of a graph with multiple components, and % then highlight the graph nodes and edges based on the search results. % % Create and plot a directed graph. This graph has two weakly connected % components. % Copyright 2015 The MathWorks, Inc. s = [1 1 2 2 2 3 4 7 8 8 8 8]; t = [3 4 7 5 6 2 6 2 9 10 11 12]; G = digraph(s,t); p = plot(G,'Layout','layered'); %% % c = conncomp(G,'Type','weak') %% % Perform a breadth-first search of the graph starting at node 2, and flag % the |'edgetonew'|, |'edgetofinished'|, and |'startnode'| events. Specify % |Restart| as |true| to make the search restart whenever there are % remaining nodes that cannot be reached. events = {'edgetonew','edgetofinished','startnode'}; T = bfsearch(G,2,events,'Restart',true) %% % When |Restart| is |true|, the |'startnode'| event returns information % about where and when the algorithm restarts the search. % % Highlight the graph based on event: % % * Color the starting nodes red. % * Green edges are for |'edgetonew'| % * Black edges are for |'edgetofinished'| % edgenew = T.Edge(T.Event == 'edgetonew',:); edgefin = T.Edge(T.Event == 'edgetofinished',:); highlight(p,edgenew(:,1),edgenew(:,2),'EdgeColor','g') highlight(p,edgefin(:,1),edgefin(:,2),'EdgeColor','k') highlight(p,T.Node(~isnan(T.Node)),'NodeColor','r')