기타/코딩테스트

(코테) 프로그래머스_기둥과 보 설치 *시물레이션+구현

불광동 물주먹 2025. 8. 2. 19:52

 

 

 

 

 

 

 

import java.util.*;

class Solution {
    public int[][] solution(int n, int[][] build_frame) {
        Set<String> setStruct = new HashSet<>();

        for (int[] frame : build_frame) {
            int x = frame[0];
            int y = frame[1];
            int a = frame[2];
            int b = frame[3];
            String key = x + "," + y + "," + a;

            if (b == 1) { // 설치
                setStruct.add(key);
                if (!isValid(setStruct)) {
                    setStruct.remove(key); // 조건 안 맞으면 설치 취소
                }
            } else { // 삭제
                setStruct.remove(key);
                if (!isValid(setStruct)) {
                    setStruct.add(key); // 조건 안 맞으면 복원
                }
            }
        }

        // 구조물 정렬
        List<int[]> sortList = new ArrayList<>();
        for (String str : setStruct) {
            String[] parts = str.split(",");
            int x = Integer.parseInt(parts[0]);
            int y = Integer.parseInt(parts[1]);
            int a = Integer.parseInt(parts[2]);
            sortList.add(new int[]{x, y, a});
        }

        sortList.sort((a1, a2) -> {
            if (a1[0] != a2[0]) return a1[0] - a2[0];
            if (a1[1] != a2[1]) return a1[1] - a2[1];
            return a1[2] - a2[2];
        });

        return sortList.toArray(new int[0][]);
    }

    public boolean isValid(Set<String> setStruct) {
        for (String str : setStruct) {
            String[] parts = str.split(",");
            int x = Integer.parseInt(parts[0]);
            int y = Integer.parseInt(parts[1]);
            int a = Integer.parseInt(parts[2]);

            if (a == 0) { // 기둥
                if (y == 0 ||
                    setStruct.contains(x + "," + (y - 1) + ",0") || // 아래 기둥
                    setStruct.contains((x - 1) + "," + y + ",1") || // 왼쪽 보
                    setStruct.contains(x + "," + y + ",1")) {       // 오른쪽 보
                    continue;
                }
                return false;
            } else { // 보
                if (setStruct.contains(x + "," + (y - 1) + ",0") || // 왼쪽 기둥
                    setStruct.contains((x + 1) + "," + (y - 1) + ",0") || // 오른쪽 기둥
                    (setStruct.contains((x - 1) + "," + y + ",1") &&
                     setStruct.contains((x + 1) + "," + y + ",1"))) {
                    continue;
                }
                return false;
            }
        }
        return true;
    }
}