Skip to content

Commit 1ff961b

Browse files
refactor 323
1 parent 472087c commit 1ff961b

File tree

1 file changed

+36
-32
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+36
-32
lines changed

src/main/java/com/fishercoder/solutions/_323.java

Lines changed: 36 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
import java.util.Queue;
77

88
/**
9+
* 323. Number of Connected Components in an Undirected Graph
10+
*
911
* Given n nodes labeled from 0 to n - 1 and 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.
1012
1113
Example 1:
@@ -28,49 +30,51 @@
2830
You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
2931
*/
3032
public class _323 {
33+
public static class Solution1 {
3134

32-
public int countComponents(int n, int[][] edges) {
33-
if (n <= 1) {
34-
return n;
35-
}
35+
public int countComponents(int n, int[][] edges) {
36+
if (n <= 1) {
37+
return n;
38+
}
3639

37-
List<List<Integer>> adList = new ArrayList<List<Integer>>();
38-
for (int i = 0; i < n; i++) {
39-
adList.add(new ArrayList<Integer>());
40-
}
40+
List<List<Integer>> adList = new ArrayList<>();
41+
for (int i = 0; i < n; i++) {
42+
adList.add(new ArrayList<>());
43+
}
4144

42-
for (int[] edge : edges) {
43-
adList.get(edge[0]).add(edge[1]);
44-
adList.get(edge[1]).add(edge[0]);
45-
}
45+
for (int[] edge : edges) {
46+
adList.get(edge[0]).add(edge[1]);
47+
adList.get(edge[1]).add(edge[0]);
48+
}
4649

47-
for (List<Integer> list : adList) {
48-
for (int i : list) {
49-
System.out.print(i + ", ");
50+
for (List<Integer> list : adList) {
51+
for (int i : list) {
52+
System.out.print(i + ", ");
53+
}
54+
System.out.println();
5055
}
51-
System.out.println();
52-
}
5356

54-
boolean[] visited = new boolean[n];
55-
int count = 0;
56-
for (int i = 0; i < n; i++) {
57-
if (!visited[i]) {
58-
count++;
59-
Queue<Integer> q = new LinkedList<Integer>();
60-
q.offer(i);
61-
while (!q.isEmpty()) {
62-
int index = q.poll();
63-
visited[index] = true;
64-
for (int j : adList.get(index)) {
65-
if (!visited[j]) {
66-
q.offer(j);
57+
boolean[] visited = new boolean[n];
58+
int count = 0;
59+
for (int i = 0; i < n; i++) {
60+
if (!visited[i]) {
61+
count++;
62+
Queue<Integer> q = new LinkedList<>();
63+
q.offer(i);
64+
while (!q.isEmpty()) {
65+
int index = q.poll();
66+
visited[index] = true;
67+
for (int j : adList.get(index)) {
68+
if (!visited[j]) {
69+
q.offer(j);
70+
}
6771
}
6872
}
6973
}
7074
}
71-
}
7275

73-
return count;
76+
return count;
77+
}
7478
}
7579

7680
}

0 commit comments

Comments
 (0)