|
| 1 | +``` |
| 2 | +package algo; |
| 3 | +
|
| 4 | +
|
| 5 | +/** |
| 6 | + * Union - Find / 합집합 찾기 ★ |
| 7 | + * 1) Union |
| 8 | + * ex) 각 노드는 우선 자기 자신을 부모로 갖는다 1 =1을 2 =2를 부모로... |
| 9 | + * 만약 1과 2가 연결되었다면 작은 쪽을 부모로 갖는다. 1의 부모는 그대로 1 / 2의 부모는 1 => 1과 2는 연결된 상태 |
| 10 | + * 추가로 2와 3이 연결된 상태라면 2의 부모는 그대로 1 / 3의 부모는 2 => 2와 3은 연결된 상태 |
| 11 | + * |
| 12 | + * 2) Find |
| 13 | + * 그럼 1,2,3,4가 서로 같은 집합인지 찾으려면? |
| 14 | + * - 각 숫자의 부모를 찾는다 |
| 15 | + * - 쭉 부모를 찾아 따라가다 부모가 자기자신이라면 stop |
| 16 | + * 1의 부모는 = 1 |
| 17 | + * 2의 부모는 = 1 |
| 18 | + * 3의 부모는 2 / 2의부모는 1 = 1 |
| 19 | + * - 1,2,3은 최종적으로 부모가 같으니 같은 집합 |
| 20 | + * 4의 부모는 4 |
| 21 | + * 1,2,3 /// 4 |
| 22 | + * */ |
| 23 | +public class Main { |
| 24 | +
|
| 25 | + static int[] parent = new int[9]; // 1부터 시작하기 위해 |
| 26 | +
|
| 27 | + static public void union(int first, int second) { |
| 28 | + // 여기 들어온다는건 first와 second 둘을 연결하겠다는 뜻 |
| 29 | + int a = getParent(first); |
| 30 | + int b = getParent(second); |
| 31 | + if (a <= b) { |
| 32 | + parent[b] = a; |
| 33 | + } else { |
| 34 | + parent[a] = b; |
| 35 | + } |
| 36 | + } |
| 37 | +
|
| 38 | + static public int getParent(int target) { |
| 39 | + // 부모를 찾는 |
| 40 | + if (parent[target] == target) { |
| 41 | + return target; |
| 42 | + } else { |
| 43 | + return getParent(parent[target]); |
| 44 | + } |
| 45 | + } |
| 46 | +
|
| 47 | + static public boolean find(int first, int second) { |
| 48 | + // 둘이 합집합인가?를 찾는 |
| 49 | + int a = getParent(first); |
| 50 | + int b = getParent(second); |
| 51 | + if (a == b) { |
| 52 | + return true; |
| 53 | + } else { |
| 54 | + return false; |
| 55 | + } |
| 56 | + } |
| 57 | + public static void main(String[] args) { |
| 58 | + for (int i = 1; i < parent.length; i++) { |
| 59 | + parent[i] = i; |
| 60 | + } |
| 61 | +
|
| 62 | + union(1, 2); |
| 63 | + union(2, 3); |
| 64 | + union(3, 4); |
| 65 | +
|
| 66 | + // 그럼 1,2,3,4 // 5,6,7,8 두 집합으로 나뉠 것 |
| 67 | +
|
| 68 | + union(5, 6); |
| 69 | + union(6, 7); |
| 70 | + union(7, 8); |
| 71 | +
|
| 72 | + System.out.println("1,4는 연결되어있나?" + find(1, 4)); |
| 73 | + System.out.println("5,8은 연결되어있나?" + find(5, 8)); |
| 74 | + //true |
| 75 | +
|
| 76 | + System.out.println("1,5는 연결되어있나?" + find(1, 5)); |
| 77 | + //false |
| 78 | + union(1,5); |
| 79 | + System.out.println("1,5는 연결되어있나?" + find(1, 5)); |
| 80 | + //true |
| 81 | +
|
| 82 | + } |
| 83 | +} |
| 84 | +
|
| 85 | +``` |
0 commit comments