N皇后问题-JAVA版
算法描述:
TODO
代码实现:
package com.dicuu.algorithm;
import java.util.Arrays;
import java.util.Scanner;
public class NQueen {
private static int queenNum;
private static int[] hash;
private static int count = 0;
public static void placeQueen(int m) {
if (m > queenNum) {
count++;
for (int i = 1; i <= queenNum; i++) {
System.out.print(hash[i]);
}
System.out.println();
System.out.println(Arrays.toString(hash));
for (int i = 1; i <= queenNum; i++) {
int column = hash[i];
for (int j = 1; j <= queenNum; j++) {
if (j != column) {
System.out.print("* ");
} else {
System.out.print("Q ");
}
}
System.out.println();
}
return;
}
for (int i = 1; i <= queenNum; i++) {
if (!isConfilct(m, i)) {
hash[m] = i;
placeQueen(m + 1);
hash[m] = -1;
}
}
}
private static boolean isConfilct(int row, int column) {
if (row == 1) {
return false;
}
for (int i = 1; i < row; i++) {
if (hash[i] == column || (column - row) == (hash[i] - i) || (row - column) == (i - hash[i])
|| (row + column) == (hash[i] + i)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
queenNum = sc.nextInt();
hash = new int[queenNum + 1];
Arrays.fill(hash, -1);
placeQueen(1);
System.out.println(count);
}
}
该页面评论已关闭