[Algorithm - Baekjoon] 9663번 N-Queen

nunu·2023년 8월 4일
0

Algorithm

목록 보기
54/142

문제

N-Queen 문제는 크기가 N × N인 체스판 위에 퀸 N개를 서로 공격할 수 없게 놓는 문제이다.

N이 주어졌을 때, 퀸을 놓는 방법의 수를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 N이 주어진다. (1 ≤ N < 15)

출력

첫째 줄에 퀸 N개를 서로 공격할 수 없게 놓는 경우의 수를 출력한다.

예제1 - 입력

8

예제1 - 출력

92

제출 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    static int n, cnt = 0;
    static int[] board;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        n = Integer.parseInt(br.readLine());
        br.close();

        board = new int[n];
        nQueen(0);
        System.out.println(cnt);
    }
    static void nQueen(int depth) {
        if (depth == n) {
            cnt++;
            return;
        }
        for (int i = 0; i < n; i++) {
            board[depth] = i;

            if(possible(depth))
                nQueen(depth + 1);
        }
    }
    static boolean possible(int depth) {
        for (int i = 0; i < depth; i++) {
            if (board[depth] == board[i])
                return false;
            else if (Math.abs(depth - i) == Math.abs(board[depth] - board[i]))
                return false;
        }
        return true;
    }
}

참고 링크 : https://velog.io/@ilil1/%EB%B0%B1%EC%A4%80-9663%EB%B2%88-java
https://st-lab.tistory.com/118

profile
Hello, I'm nunu

0개의 댓글