八皇后问题 java实现
程序员文章站
2022-07-04 21:03:16
import java.util.Scanner;public class EightQueen {private static int m = 0;//设置皇后的个数public static int n;//棋盘public static int[][] pan;//展示棋盘public static void show() {System.out.println("第" + (++m) + "种解法为:");for(int i = 0; i < n;...
import java.util.Scanner;
public class EightQueen {
private static int m = 0;
//设置皇后的个数
public static int n;
//棋盘
public static int[][] pan;
//展示棋盘
public static void show() {
System.out.println("第" + (++m) + "种解法为:");
for(int i = 0; i < n; i ++) {
for(int j = 0; j < n; j ++) {
System.out.print(pan[i][j] + "\t");
}
System.out.println();
}
}
//测试位置
public static boolean check(int row, int col, int n) {
//测试列
for(int i = row - 1; i >= 0; i --) {
if(pan[i][col] == 1) {
return false;
}
}
//测试左上斜线
for(int i = row - 1, j = col - 1; i >= 0 && j >= 0; i --, j -- ) {
if(pan[i][j] == 1) {
return false;
}
}
//测试右上斜线,注意这里是 j++
for(int i = row - 1, j = col + 1; i >= 0 && j < n; i --, j ++ ) {
if(pan[i][j] == 1) {
return false;
}
}
return true;
}
//摆放棋子
public static void put(int row, int n) {
for(int i = 0; i < n; i ++) {
if(check(row, i, n)) {
//假设成立,开门
pan[row][i] = 1;
if(row < n - 1) {
put(row + 1, n);
}else {
show();
}
//关门,如果失败,可以进行回溯
pan[row][i] = 0;
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入皇后的个数:");
n = in.nextInt();
pan = new int[n][n];
put(0, n);
System.out.println("总共有" + m + "种情况");
}
}
本文地址:https://blog.csdn.net/qq_44652489/article/details/110156309