π [λ°±μ€μκ³ λ¦¬μ¦ νμ΄] Q.9663 N-Queen λ¬Έμ νμ΄ - java
π λ¬Έμ
https://www.acmicpc.net/problem/9663
N-Queen λ¬Έμ λ ν¬κΈ°κ° N Γ NμΈ μ²΄μ€ν μμ νΈ Nκ°λ₯Ό μλ‘ κ³΅κ²©ν μ μκ² λλ λ¬Έμ μ΄λ€.
Nμ΄ μ£Όμ΄μ‘μ λ, νΈμ λλ λ°©λ²μ μλ₯Ό ꡬνλ νλ‘κ·Έλ¨μ μμ±νμμ€.
π μ κ·Όλ²
Q.9663 N-Queen λ¬Έμ μ λλ€.
λ°±νΈλνΉ μ νμ λνμ μΈ λ¬Έμ μ λλ€.
N * N 체μ€ν μμ νΈ Nκ°λ₯Ό μλ‘ κ³΅κ²©ν μ μκ² λλ λ°©λ²μ ꡬνλ λ¬Έμ μ λλ€.
μ°μ νΈμ λ°°μΉκ° λΆκ°λ₯ν κ²½μ°λ κΈ°μ‘΄μ νΈμ μ리μ
κ°λ‘μ μΈλ‘μ λΆκ°λ₯νκ³ λν λκ°μ μ μμΉμλ λ°°μΉκ° λΆκ°λ₯ν©λλ€.
μ²μμ 체μ€ν N*Nμ 2μ°¨μ λ°°μ΄λ‘ μ μΈνμ¬
λ°±νΈλνΉμ μ§ννμμ§λ§ νΈμ λ μ μλμ§ μλμ§ νμΈν λ μ΄μ€ for λ¬Έμ μ¬μ©νμ¬ μκ°μ΄κ³Όκ° λ¬μ΅λλ€.
κ·Έλμ
2μ°¨μ λ°°μ΄λ‘ μ μΈν 체μ€νμ
1μ°¨μ λ°°μ΄λ‘ μ μΈνμ¬
κ° μΈλ±μ€μλ rowλ‘ board[row] λ column κ°μΌλ‘ λ£μ΄μ£Όμ΄
λ°±νΈλνΉμ ν΅ν΄ νμ΄κ° κ°λ₯νμ΅λλ€.
π» μ½λ
2μ°¨μ λ°°μ΄ νμ΄ (μκ° μ΄κ³Ό)
public class Main_9663_1 {
static int N, ans;
static boolean[][] board;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
board = new boolean[N][N];
ans = 0;
solve(0);
System.out.println(ans);
}
public static void solve(int r) {
if (r == N) {
ans++;
return;
}
for (int c = 0; c < N; c++) {
if (check(r, c)) {
board[r][c] = true;
solve(r + 1);
board[r][c] = false;
}
}
}
public static boolean check(int r, int c) {
if (board[r][c])
return false;
for (int i = 0; i < N; i++) {
if (board[i][c])
return false;
for (int j = 0; j < N; j++) {
if(Math.abs(r-i) == Math.abs(c-j) && board[i][j]){
return false;
}
}
}
return true;
}
}
1μ°¨μ λ°°μ΄ νμ΄ (μ λ΅)
public class Main_9663_2 {
static int N, ans;
static int[] board;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
board = new int[N];
ans = 0;
solve(0);
System.out.println(ans);
}
public static void solve(int row) {
if(N==row){
ans++;
return;
}
for(int i=0; i<N; i++){
board[row] = i;
if(check(row)){
solve(row+1);
}
}
}
public static boolean check(int row) {
for(int i=0; i<row; i++){
if(board[i] == board[row] || Math.abs(board[i]- board[row]) == Math.abs(i-row)){
return false;
}
}
return true;
}
}