Topic:
find the connected features of a non-graph summary
Please find out the number of connected features in the graph.
Each node in the diagram contains 1 tags and a list of its neighbors. (a linked node (or node) of a non-graph is a sub-graph where any two vertices are connected by a path and are not connected to other vertices in the super graph.) )
Sample Example
Given diagram:
A------B C \ | | \ | | \ | | \ | | D E
Return {A,B,D}, {C,E}
. There are 2 connected elements, namely{A,B,D}, {C,E}
Solving:
Breadth First + recursive, not written, program source
Java Program:
/*** Definition for undirected graph. * Class Undirectedgraphnode {* int label; * ARRAYLIST<UNDIRECTEDGRAPHN Ode> Neighbors; * Undirectedgraphnode (int x) {label = x; neighbors = new arraylist<undirectedgraphnode> ();}}; */ Public classSolution {/** * @paramnodes A array of undirected graph node *@returna connected set of a undirected graph*/ PublicList<list<integer>> Connectedset (arraylist<undirectedgraphnode>nodes) { //Write Your code here intm =nodes.size (); Map<undirectedgraphnode, boolean> visited =NewHashmap<>(); for(Undirectedgraphnode node:nodes) {visited.put (node,false); } List<List<Integer>> result =NewArraylist<>(); for(Undirectedgraphnode node:nodes) {if(visited.get (node) = =false) {BFS (node, visited, result); } } returnresult; } Public voidBFS (Undirectedgraphnode node, Map<undirectedgraphnode, Boolean> visited, list<list<integer>>result) {List<integer>row =NewArraylist<>(); Queue<UndirectedGraphNode> queue =NewLinkedlist<>(); Visited.put (node,true); Queue.offer (node); while(!Queue.isempty ()) {undirectedgraphnode U=Queue.poll (); Row.add (U.label); for(Undirectedgraphnode v:u.neighbors) {if(Visited.get (v) = =false) {visited.put (V,true); Queue.offer (v); }}} collections.sort (row); Result.add (row); }}
View Code
Total time: 7732 ms
Python program:
Lintcode Easy title: Find the Connected Component in the undirected graph to find the connected features of the non-graph summary