|
| 1 | +import org.assertj.core.api.Assertions; |
| 2 | +import org.junit.jupiter.api.DisplayName; |
| 3 | +import org.junit.jupiter.api.Test; |
| 4 | + |
| 5 | +import java.util.HashSet; |
| 6 | +import java.util.Set; |
| 7 | + |
| 8 | +public class CountConnectedComponents { |
| 9 | + |
| 10 | + public int countComponents(int n, int[][] edges) { |
| 11 | + final int[] relation = new int[n]; |
| 12 | + for (int i = 0; i < n ; i++) { |
| 13 | + relation[i] = i; |
| 14 | + } |
| 15 | + |
| 16 | + int result = n; |
| 17 | + for (int[] edge : edges) { |
| 18 | + if (union(relation, edge) == 1) { |
| 19 | + result--; |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + return result; |
| 24 | + } |
| 25 | + |
| 26 | + private int union(int[] relation, int[] edge) { |
| 27 | + int parent1 = find(relation, edge[0]); |
| 28 | + int parent2 = find(relation, edge[1]); |
| 29 | + |
| 30 | + if (parent1 == parent2) { |
| 31 | + return 0; |
| 32 | + } |
| 33 | + |
| 34 | + if (parent1 < parent2) { |
| 35 | + relation[parent2] = parent1; |
| 36 | + } else { |
| 37 | + relation[parent1] = parent2; |
| 38 | + } |
| 39 | + return 1; |
| 40 | + } |
| 41 | + |
| 42 | + private int find(int[] relation, int node) { |
| 43 | + int result = node; |
| 44 | + while (relation[result] != result) { |
| 45 | + relation[result] = relation[relation[result]]; |
| 46 | + result = relation[result]; |
| 47 | + } |
| 48 | + return result; |
| 49 | + } |
| 50 | + |
| 51 | + @Test |
| 52 | + @DisplayName("입력받은 노드와 간선을 통해 그래프의 개수를 반환한다") |
| 53 | + void graphCount() { |
| 54 | + int actual = countComponents(3, new int[][]{ {0,1}, {0,2} }); |
| 55 | + Assertions.assertThat(actual).isEqualTo(1); |
| 56 | + |
| 57 | + int actual1 = countComponents(6, new int[][]{ {0,1}, {1,2}, {2,3}, {4,5} }); |
| 58 | + Assertions.assertThat(actual1).isEqualTo(2); |
| 59 | + |
| 60 | + int actual2 = countComponents(6, new int[][]{ {0,1}, {2,3}, {4,5}, {1,2}, {3,4} }); |
| 61 | + Assertions.assertThat(actual2).isEqualTo(1); |
| 62 | + } |
| 63 | +} |
0 commit comments