高手指点指点把,看了一天了都不知道哪里有问题,输出一直为0
查看原帖
高手指点指点把,看了一天了都不知道哪里有问题,输出一直为0
953931
qingqing0324楼主2024/3/25 18:28

大佬指点一二,为什么输出一直都是0,找不到原因。。。

package 蓝桥杯;

import java.util.Scanner;

public class 八皇后_搜索 {
	static int n;
	static int a[];
	static int c[];// 列判重
	static int p[];// 右对角线判重
	static int q[];// 左对角线判重
	static int count;

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		n = input.nextInt();
		a = new int[n + 10];// 数组下表代表行,存的数字代表列
		c = new int[n + 10];// 下表为列,内容为0或1判重
		p = new int[2 * n + 10];// 下表为右对角线,内容为0或1判重
		q = new int[2 * n + 10];// 下表为左对角线,内容为0或1判重
		dfs(1);
		System.out.println(count);
	}

	public static void print() {
		if (count <= 3) {// 大于3个解就不再输出
			for (int i = 1; i <= n; i++) {// 打印出解的每一列
				System.out.print(a[i] + " ");
			}
			System.out.println();
		}
	}

	public static void dfs(int i) {
		if (i > n) {// i代表行,每当i>n代表有一个解
			count++;
			print();
			return;
		}
		for (int j = 1; j <= n; j++) {
			if (c[j] == 1 || p[i + j] == 1 || p[i - j + n] == 1) {
				continue;
			}
			a[i] = j;// 第i行 第j列
			c[j] = 1;
			p[i + j] = 1;
			p[i - j + n] = 1;
			dfs(i + 1);
			c[j] = 0;
			p[i + j] = 0;
			p[i - j + n] = 0;
		}
	}

}

2024/3/25 18:28
加载中...