약간 삼성 B형 느낌이 났던 문제.
구현 문제라서 시간이 좀 걸렸고, 한 글자를 잘못 써서 헤멨던 문제다.
구현 문제를 풀 때는 꼼꼼하게, 주석을 작성하면서 푸는 습관을 들여야겠다.
import java.util.*;
class Solution {
static String[][] table;
static int[] parent;
public static String[] solution(String[] commands) {
List<String> answers = new ArrayList<>();
table = new String[50][50];
parent = new int[2500];
for(int i = 0; i < 2500; i++) {
parent[i] = i;
}
for(int i = 0; i < commands.length; i++) {
String[] command = commands[i].split(" ");
switch(command[0]) {
case "UPDATE":
if(command.length == 4) {
int r = Integer.parseInt(command[1]) - 1;
int c = Integer.parseInt(command[2]) - 1;
String v = command[3];
update(r, c, v);
} else {
String v1 = command[1];
String v2 = command[2];
updateAll(v1, v2);
}
break;
case "MERGE":
int r1 = Integer.parseInt(command[1]) - 1;
int c1 = Integer.parseInt(command[2]) - 1;
int r2 = Integer.parseInt(command[3]) - 1;
int c2 = Integer.parseInt(command[4]) - 1;
merge(r1, c1, r2, c2);
break;
case "UNMERGE":
int r3 = Integer.parseInt(command[1]) - 1;
int c3 = Integer.parseInt(command[2]) - 1;
unmerge(r3, c3);
break;
case "PRINT":
int r4 = Integer.parseInt(command[1]) - 1;
int c4 = Integer.parseInt(command[2]) - 1;
if(table[r4][c4] == null) {
answers.add("EMPTY");
} else {
answers.add(table[r4][c4]);
}
break;
}
}
String[] answer = new String[answers.size()];
for(int i = 0; i < answer.length; i++) {
answer[i] = answers.get(i);
}
return answer;
}
public static void update(int r, int c, String value) {
int stdCell = find(r * 50 + c);
for(int i = 0; i < 2500; i++) {
if(parent[i] == stdCell) {
int r1 = i / 50;
int c1 = i % 50;
table[r1][c1] = value;
}
}
}
public static void updateAll(String v1, String v2) {
for(int r = 0; r < 50; r++) {
for(int c = 0; c < 50; c++) {
if(v1.equals(table[r][c])) {
table[r][c] = v2;
}
}
}
}
public static void merge(int r1, int c1, int r2, int c2) {
int rc1 = r1 * 50 + c1;
int rc2 = r2 * 50 + c2;
int prc1 = find(rc1);
int prc2 = find(rc2);
if(prc1 == prc2) return;
parent[prc2] = prc1;
String value = table[r1][c1] != null ? table[r1][c1] : table[r2][c2];
for(int i = 0; i < 2500; i++) {
if(find(i) == prc1) {
int r = i / 50;
int c = i % 50;
table[r][c] = value;
}
}
}
public static int find(int a) {
if(parent[a] == a) return a;
return parent[a] = find(parent[a]);
}
public static void unmerge(int r, int c) {
String v = table[r][c];
int stdCell = find(r * 50 + c);
for(int i = 0; i < 2500; i++) {
if(parent[i] == stdCell) {
int r1 = i / 50;
int c1 = i % 50;
parent[i] = i;
table[r1][c1] = null;
}
}
table[r][c] = v;
}
}
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 등산 코스 정하기 (2) | 2024.12.09 |
---|---|
[프로그래머스] 표현 가능한 이진트리 (0) | 2024.11.11 |
[프로그래머스] 택배 배달과 수거하기 (3) | 2024.10.26 |
[프로그래머스] 블록 이동하기 (0) | 2024.10.20 |
[프로그래머스] 합승 택시 요금 (1) | 2024.10.13 |