N-Queen 문제는 크기가 N × N인 체스판 위에 퀸 N개를 서로 공격할 수 없게 놓는 문제이다.
N이 주어졌을 때, 퀸을 놓는 방법의 수를 구하는 프로그램을 작성하시오.
첫째 줄에 N이 주어진다. (1 ≤ N < 15)
첫째 줄에 퀸 N개를 서로 공격할 수 없게 놓는 경우의 수를 출력한다.
8
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