Find the number connected component in the undirected graph. Each node in the graph contains a label and a list of its neighbors. (a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph.)
Notice
Each connected component should sort by label.
Example
Given graph:
A------B C
\ | |
\ | |
\ | |
\ | |
D E
Return{A,B,D}, {C,E}. Since there are two connected component which is{A,B,D}, {C,E}
323. Number of Connected Components in an Undirected Graph
Givennnodes labeled from0ton - 1and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.
Note:
You can assume that no duplicate edges will appear inedges. Since all edges are undirected,[0, 1]is the same as[1, 0]and thus will not appear together inedges.
publicintcountComponents(int n,int[][] edges) {if (edges ==null||edges.length==0|| edges[0].length==0) {return n; }// <node, adjList>ArrayList[] graph =newArrayList[n];for (int i =0; i < n; i++) { graph[i] =newArrayList<Integer>(); }// turn the edges to adjacent listfor (int[] edge : edges) { graph[edge[0]].add(edge[1]); graph[edge[1]].add(edge[0]); }// do bfs to find component numberint cnt =0;HashSet<Integer> visited =newHashSet<>();for (int i =0; i < n; i++) {if (!visited.contains(i)) {bfs(graph, visited, i); cnt++; } }return cnt;}privatevoidbfs(ArrayList[] graph,HashSet<Integer> visited,int start) {Queue<Integer> queue =newLinkedList<>();queue.offer(start);visited.add(start);while (!queue.isEmpty()) {Integer cur =queue.poll();for (Object nei : graph[cur]) {if (!visited.contains((Integer)nei)) {visited.add((Integer)nei);queue.offer((Integer)nei); } } }}