[ 문제 ]
- Queen 문제는 크기가 N × N인 체스판 위에 퀸 N개를 서로 공격할 수 없게 놓는 문제이다.
- 주어졌을 때, 퀸을 놓는 방법의 수를 구하는 프로그램을 작성하시오.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Queue;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static int[][] dir;
static boolean[][] visited;
static int N;
static int total ;
public static void main(String[] args) throws IOException {
N = Integer.parseInt(br.readLine());
visited = new boolean[N][N];
dir = new int[][]{{1, 1}, {-1, 1}, {1, -1}, {-1, -1}};
total = 0;
btc(0, 0, 0);
System.out.println(total);
}
public static void btc(int r, int c, int tmp){
if(tmp == N){
total += 1;
return;
}
for(int i = 0 ; i < N ; i ++){
if(isVal(r, i)){
visited[r][i] = true;
btc(r + 1, i, tmp + 1);
visited[r][i] = false;
}
}
}
public static boolean isVal(int r, int c){
for(int i = 0 ; i < N ; i ++){
// 위 아래 확인
if(visited[r][i] || visited[i][c]){
return false;
}
}
for(int j = 0 ; j < 4 ; j ++){
// 대각선 확인
int drow = r + dir[j][0];
int dcol = c + dir[j][1];
while(inRange(drow, dcol)){
if(visited[drow][dcol]){
//true 인 경우
return false;
}
drow += dir[j][0];
dcol += dir[j][1];
}
}
return true;
}
public static boolean inRange(int r, int c){
return r >= 0 && r < N && c >= 0 && c < N;
}
}