요깨비's LAB

[프로그래머스, Java] 자물쇠와 열쇠 본문

알고리즘(Java)/프로그래머스

[프로그래머스, Java] 자물쇠와 열쇠

요깨비 2021. 9. 23. 18:39

class Solution {
    static int len;
    static int keyLen;
    static int lockLen;
    static int[][] map;

    public boolean solution(int[][] key, int[][] lock) {
        boolean answer = true;

        keyLen = key.length;
        lockLen = lock.length;
        len = lockLen + (2 * (lockLen - 1));
//        len = keyLen + (2 * (keyLen - 1)); => 착오
        

        map = new int[len][len];
        int lockZeroCnt = 0;

        for (int i = 0; i < lockLen; i++) {
            for (int j = 0; j < lockLen; j++) {
                map[i + (lockLen - 1)][j + (lockLen - 1)] = lock[i][j];

                if (lock[i][j] == 0) {
                    lockZeroCnt++;
                }
            }
        }

        // 오른쪽 이동
        moveDown:
        for (int down = 0; down <= len - keyLen; down++) {
            // 아래 이동
            moveRight:
            for (int right = 0; right <= len - keyLen; right++) {
                // 90도 회전
                rotate:
                for (int rotate = 0; rotate < 4; rotate++) {
                    if (check(down, right, lockZeroCnt, key)) {
                        return true;
                    }

                    key = rotateKey(key, keyLen);
                }
            }
        }

        return false;
    }

    public boolean check(int down, int right, int lockZeroCnt, int[][] key) {
        for (int i = 0; i < keyLen; i++) {
            for (int j = 0; j < keyLen; j++) {
                if (map[down + i][right + j] + key[i][j] > 1) {
                    return false;
                }

                if (
                        (lockLen - 1 <= down + i && i + down <= len - lockLen) &&
                        (lockLen - 1 <= j + right && j + right <= len - lockLen) &&
                                map[down + i][right + j] == 0 &&
                                key[i][j] == 1
                ) {
                	lockZeroCnt--;
                }
            }
        }

        return lockZeroCnt == 0 ? true : false;
    }

    public int[][] rotateKey(int[][] key, int keyLen) {
        int[][] rotatedMap = new int[keyLen][keyLen];

        for (int i = 0; i < keyLen; i++) {
            for (int j = 0; j < keyLen; j++) {
                rotatedMap[i][j] = key[keyLen - 1 - j][i];
            }
        }

        return rotatedMap;
    }
}
Comments