알고리즘

[프로그래머스] 단체사진 찍기 - java

minkang 2021. 9. 23. 12:05

https://programmers.co.kr/learn/courses/30/lessons/1835

 

코딩테스트 연습 - 단체사진 찍기

단체사진 찍기 가을을 맞아 카카오프렌즈는 단체로 소풍을 떠났다. 즐거운 시간을 보내고 마지막에 단체사진을 찍기 위해 카메라 앞에 일렬로 나란히 섰다. 그런데 각자가 원하는 배치가 모두

programmers.co.kr

class Solution {
    int answer;
    char[] person = new char[] {'A', 'C', 'F', 'J', 'M', 'N', 'R', 'T'};
    public int solution(int n, String[] data) {
        int personCnt = 8;
        answer = 0;
        boolean[] visited = new boolean[personCnt];
        int[] order = new int['T'+1];
        permutation(0, personCnt, visited, order, data);
        return answer;
    }
    
    void permutation(int depth, int personCnt, boolean[] visited, int[] order, String[] data){
        if(depth == personCnt){
            if(isOk(order, data) == true){
                answer++;
            }
            return;
        }
        
        for(int i=0; i<personCnt; i++){
            if(visited[i] == true){
                continue;
            }
            visited[i] = true;
            order[person[i]] = depth;
            permutation(depth+1, personCnt, visited, order, data);
            visited[i] = false;
        }
    }
    
    boolean isOk(int[] order, String[] data) {
        for(int i=0; i<data.length; i++){
            char personA = data[i].charAt(0);
            char personB = data[i].charAt(2);
            int positionA = order[personA];
            int positionB = order[personB];
            int distance = data[i].charAt(4)-'0';
            char operatorType = data[i].charAt(3);
            
            int distanceAB = Math.abs(positionA - positionB) -1;
            if(operatorType == '='){
                if(distanceAB != distance){
                    return false;
                }
            }
            else if(operatorType == '<'){
                if(distanceAB >= distance){
                    return false;
                }
            }
            else if(operatorType == '>'){
                if(distanceAB <= distance){
                    return false;
                }
            }
        }
        return true;
    }
}

{A, C, F, J, M, N, R, T}

단체사진을 찍는 자리를 정하기 위해

8명의 사람을 순열을 돌려 자리를 지정해주었습니다.

 

자리는 int[] order = new int['T'+1];로 선언하여

ACFJMNRT의 순서의 경우

order[A] = 0;

order[C] = 1;

order[F] = 2;

와 같은 방식으로 자리를 저장했습니다.

조건 체크할때 A의 위치를 찾을때 순회하지 않기 위해서입니다.

 

8명의 사람이 자리가 지정이 다 되었을때

제시한 조건과 부합한지 체크합니다.