https://www.acmicpc.net/problem/9663
백트래킹의 대표적인 문제다.
맨 첫번째 줄부터 하나씩 퀸을 놓은 다음, 그 다음 줄에 퀸을 놓는데 만약 퀸을 놓을 수 없는 자리면 그 칸은 더이상 탐색을 하지 않고 그 줄의 다음 칸에 퀸을 놓는다.
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
static int n, m;
static int[][] queen;
static int answer = 0;
static public boolean check(int row, int col) {
for (int i = 1; i < row; i++) { //같은 열에 퀸이 있는 경우
if (queen[i][col] == 1) {
return false;
}
}
for (int i = row-1, j = col-1; i > 0 && j > 0; i--, j--) { //현재 놓은 위치에 대각선에 퀸이 있는 경우
if (queen[i][j] == 1) {
return false;
}
}
for (int i = row-1, j = col + 1; i > 0 && j <= n; i--, j++) { //현재 놓은 위치에 대각선에 퀸이 있는 경우
if (queen[i][j] == 1)
return false;
}
return true;
}
static public void nQueen(int row) {
if (row > n) {
answer++;
return;
}
for (int i = 1; i <= n; i++) {
queen[row][i] = 1;
if (check(row, i)) {
nQueen(row + 1);
}
queen[row][i] = 0;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
queen = new int[n+1][n+1];
nQueen(1);
System.out.println(answer);
}
}
check
함수를 통해 현재 칸에 퀸을 놓을 수 있는지 체크한다. 만약 놓을 수 있으면 nQueen(row + 1)
을 호출하여 다음 줄에 퀸을 놓는다.row > n
이라면, 모든 줄에 퀸을 놓은 것이므로, answer++
한다.depth == N
이면 count++
한다.arr[col] == arr[i]
Math.abs(col - i) == Math.abs(arr[col] - arr[i])
import java.util.*;
public class Main {
static int N;
static int[] arr;
static int count = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
arr = new int[N];
N_queen(0);
System.out.println(count);
}
static void N_queen(int depth) {
if(depth == N) {
count++;
return;
}
for(int i = 0; i < N; i ++) {
arr[depth] = i;
if(check(depth) == true) {
N_queen(depth + 1);
}
}
}
static boolean check(int col) {
for(int i = 0; i < col; i ++) {
if(arr[col] == arr[i]) {
return false;
}else if(Math.abs(col - i) == Math.abs(arr[col] - arr[i])) {
return false;
}
}
return true;
}
}
참고: https://st-lab.tistory.com/118
https://velog.io/@ilil1/%EB%B0%B1%EC%A4%80-9663%EB%B2%88-java