P1219八皇后(DFS+回溯)


import java.util.Scanner;
/**
 * 八皇后问题
 * 算法:DFS+回溯算法,
 * 注意,逐个遍历时间复杂度过高,数据量大时,结果正确但不符合要求。
 * 优化:以行为单位,一行放下,该行就不能再放,直接从下一行开始遍历。
 */
public class P1219_project {
	static int n, count = 0;
	static int[] cols = new int[14];// 列
	
	static int[] u 	  = new int[27];// 左上到右下对角线 i-j+n值固定
	static int[] v 	  = new int[27];// 左下到右上对角线,对角线i+j固定值
	
	static int[] a = new int[100];

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		dfs(1);
		System.out.println(count);
	}

	public static void dfs(int x) {
		if (x>n) {
			count++;
			if (count<=3) {
				for (int i=1; i<=n; i++) {
					System.out.print(a[i] + " ");
				}
				System.out.println();
			}
			return;
		}
		for (int i=1;i<=n;i++) {
			if (cols[i]==0&&   u[x-i+n]==0&&v[x+i]==0) {
				cols[i]	 = 1;
				u[x-i+n] = 1;
				v[x+i] 	 = 1;
				a[x]=i;
				
				dfs(x+1);
				// 清除前一列标记
				cols[i]	 = 0;
				u[x-i+n] = 0;
				v[x+i] 	 = 0;
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_28635317/article/details/111866063