[프로그래머스] 코딩테스트 연습 - 연습문제 Level 3 N-Queen

uoahy·2021년 10월 7일
0

Solution.java

class Solution {
    boolean[] col;
    boolean[][] diag;
    
    public int solution(int n) {
        int answer = 0;
        
        col = new boolean[n];
        diag = new boolean[2][2 * n - 1];
        
        answer = play(0, n);
        
        return answer;
    }
    
    int play(int row, int n) {
        if (row == n) return 1;
        
        int result = 0;
        
        for (int i = 0; i < n; i++) {
            if (!col[i] && !diag[0][row + i] && !diag[1][i - row + n - 1]) {
                col[i] = diag[0][row + i] = diag[1][i - row + n - 1] = true;
                result += play(row + 1, n);
                col[i] = diag[0][row + i] = diag[1][i - row + n - 1] = false;
            }
        }
        
        return result;
    }
}

출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges

0개의 댓글