- 题目
所谓N皇后问题就是:将N位皇后放在一张NxN的棋盘上,使得每位皇后都无法吃掉别的皇后,(即任意两个皇后都不在同一条横线,竖线和斜线上),问一共有多少种摆法。
- 实现及思路
package 蓝桥;
import java.util.Scanner;
public class NQueen {
static int count = 0;
static int[][] arry ;
static int n;
public static void findQueen(int row) {
if (row == n) {
count++;
print();
return;
}
for (int coulm = 0; coulm < n; coulm++) {
if (cheack(row, coulm)) {
arry[row][coulm] = 1;
findQueen(row + 1);
arry[row][coulm] = 0;
}
}
}
public static void print() {
System.out.println("第" + count + "种方法:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (arry[i][j] == 1)
System.out.print("O ");
else
System.out.print("+ ");
}
System.out.println();
}
System.out.println();
}
public static boolean cheack(int a, int b) {
for (int i = 0; i < n; i++) {
if (arry[i][b] == 1)
return false;
}
for (int i = a - 1, j = b - 1; i >= 0 & j >= 0; i--, j--) {
if (arry[i][j] == 1)
return false;
}
for (int i = a - 1, j = b + 1; i >= 0 & j < n; i--, j++) {
if (arry[i][j] == 1)
return false;
}
return true;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
arry=new int[n][n];
long startTime = System.currentTimeMillis();
findQueen(0);
System.out.println("共"+count+"种方法");
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间:" + (endTime - startTime) + "ms");
}
}