λ¬Έμ
νμ΄
μ²μμλ μμ νμμΌλ‘ μ κ·Όνμμ§λ§ μκ°μ΄κ³Όλ‘ μ€ν¨νμλ€. κ·Έλμ κ²½μ°μ μλ₯Ό μ€μ΄κΈ° μν λ°©λ²μ κ³ λ―Όνκ³ λͺ¨λ ν/μ΄μ΄ μλ μ΄μ°¨νΌ ν νμλ νλμ Queenλ§ μ¬ μ μλ€λ μ μ μ΄μ©ν΄ μ¬κ·ν¨μμ κΉμ΄λ₯Ό μ€μΌ μ μμλ€.
import java.util.Scanner;
public class NQueens {
static Scanner sc = new Scanner(System.in);
static int result = 0;
static int N = 0;
static boolean[][] check;
static int[] dx = {0, 0, -1, 1, 1 ,1 , -1, -1};
static int[] dy = {-1, 1, 0 ,0, -1, 1 , 1, -1};
public static void main(String[] args) {
N = sc.nextInt();
for (int i = 0; i < N; i++) {
check = new boolean[N][N];
check[0][i] = true;
nqueen(0,i,1);
}
System.out.println(result);
}
private static void nqueen(int x, int y, int cnt) {
if (cnt == N ) {
result += 1;
return;
}
for (int j = 0; j < check[0].length; j++) {
if (j == y || !isValid(x+1, j)) continue;
check[x+1][j] = true;
nqueen(x+1, j, cnt + 1);
check[x+1][j] = false;
}
}
static boolean isValid(int x, int y) {
for (int i = 0; i < 8; i++) {
int currentX = x;
int currentY = y;
while(true) {
currentX += dx[i];
currentY += dy[i];
if (currentX < 0 || currentX >= N || currentY < 0 || currentY >= N) break;
if (check[currentX][currentY]) {
return false;
}
}
}
return true;
}
}
μ λ΅μ λ§κΈ΄νλ° μν μκ°μ΄ λ무 μ€λ κ±Έλ €μ λ€λ₯Έ μ¬λλ€μ μ½λλ₯Ό μ°Έκ³ ν΄λ΄€λ€. λ¨Όμ 2μ°¨μ λ°°μ΄μ μ΄μ©νμ§ μκ³ 1μ°¨μ λ°°μ΄μ μ¬μ©ν΄μ μΈλ±μ€κ° νμΌλ‘ κ°μ΄ λμ μ΄μ μμΉλ₯Ό λνλ΄λλ‘ κ΅¬ννλ€λ μ , κ·Έλ¦¬κ³ λλ λμ μ μλ μμΉλ₯Ό μ°ΎκΈ° μν΄ delta λ°°μ΄μ λ§λ€μ΄μ λͺ¨λ λ°©ν₯μ λν΄ νμμ νλλ°, μ΄λ₯Ό μ΄μ©ν΄μ λμ μ μλμ§ νλ¨νλ λΆλΆμ μ΅μ ν ν λΆλΆμ΄ λμ λ€λ₯Έ λΆλΆμ΄μλ€.
μ΅μ ν ν΄λ΅
import java.util.Scanner;
public class NQueens {
static Scanner sc = new Scanner(System.in);
static int result = 0;
static int N = 0;
static int[] row;
public static void main(String[] args) {
N = sc.nextInt();
row = new int[N];
int depth = 0;
nqueen(depth);
System.out.println(result);
}
private static void nqueen(int depth) {
if (depth == N) {
result += 1;
return;
}
for (int i = 0; i < N; i++) {
row[depth] = i;
if (isValid(depth)) {
nqueen(depth + 1);
}
}
}
static boolean isValid(int depth) {
for (int i = 0; i < depth; i++) {
if (row[i] == row[depth])
return false;
if (Math.abs(row[i] - row[depth]) == Math.abs(i - depth))
return false;
}
return true;
}
}
'π Algorithm > π» λ¬Έμ νμ΄' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[λ°±μ€] 9251. LCS (0) | 2021.02.10 |
---|---|
[λ°±μ€] 11053. κ°μ₯ κΈ΄ μ¦κ°νλ λΆλΆ μμ΄ (0) | 2021.02.10 |
[λ°±μ€] 2493. ν (0) | 2021.02.04 |
[λ°±μ€] 1436. μνκ°λ μ (0) | 2021.02.03 |
[λ°±μ€] 1018. 체μ€ν λ€μ μΉ νκΈ° (0) | 2021.02.02 |
λκΈ