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}
Idea: To tell the truth, Lintcode translation I did not understand what the meaning, of course, do not know how to do. To be exact, this problem should be called finding the maximal connected sub-graphs in undirected graphs, and the algorithm used is breadth-first search. Here is a comparison of breadth-first search and depth-first search algorithms, which, incidentally, is reviewed;
http://blog.csdn.net/andyelvis/article/details/1728378
Of course the code is also I learn others, the source attached http://www.jiuzhang.com/solutions/find-the-connected-component-in-the-undirected-graph/
1 /**2 * Definition for undirected graph.3 * Class Undirectedgraphnode {4 * int label;5 * arraylist<undirectedgraphnode> neighbors;6 * Undirectedgraphnode (int x) {label = x; neighbors = new arraylist<undirectedgraphnode> ();}7 * };8 */9 Public classSolution {Ten /** One * @paramnodes A array of undirected graph node A * @returna connected set of a undirected graph - */ - PublicList<list<integer>> Connectedset (arraylist<undirectedgraphnode>nodes) { the //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<>(); A for(Undirectedgraphnode node:nodes) { at if(visited.get (node) = =false){ - BFS (node,visited,result); - } - } - returnresult; - } in Public voidBFS (Undirectedgraphnode node,map<undirectedgraphnode,boolean> visited,list<list<integer>>result) { -list<integer> row =NewArraylist<>(); toqueue<undirectedgraphnode> queue =NewLinkedlist<>(); +Visited.put (node,true); - queue.offer (node); the while(!Queue.isempty ()) { *Undirectedgraphnode U =Queue.poll (); $ Row.add (U.label);Panax Notoginseng for(Undirectedgraphnode v:u.neighbors) { - if(Visited.get (v) = =false){ theVisited.put (V,true); + Queue.offer (v); A } the } + } - collections.sort (row); $ result.add (row); $ } -}
Find the connected features of the Find-the-connected-component-in-the-undirected-graph graph summary