[HDU2553]N皇后问题(DFS)

题目链接

http://acm.hdu.edu.cn/showproblem.php?pid=2553

题意

n<=10,输出N皇后问题的方法数。

题解

  • 可以使用各种方法。这里使用DFS。
  • 使用一维数组存储棋子位置。col[i]=j表示第i行的棋子放置在j列。
  • 由于n<=10,打表10个结果在数组中即可。
  • dfs(row)表示放置第row层(从0记)的棋子。dfs return条件是到了第n层,此时方法数++;

代码

import java.util.Scanner;

public class Main {
	final static int MAXN=10;
	public static int[] means=new int[MAXN+1];
	public static int[] col=new int[MAXN+1];
	
	public static void main(String args[]) {
		//打表
		for(int i=1;i<=MAXN;++i) {
			means[i]=0;
		}
		for(int n=1;n<=MAXN;++n) {
			dfs(0,n);
		}
		
		Scanner in=new Scanner(System.in);
		int n;
		while(true) {
			n=in.nextInt();
			if(n==0) {break;}
			System.out.println(means[n]);
		}
	}
	
	public static void dfs(int row,int n) {
		if(row==n) {
			++means[n];
			return;
		}
		for(int j=0;j<n;++j) {
			col[row]=j;
			if(check(row,n)==true) {
				dfs(row+1,n);
			}
		}
	}
	
	public static boolean check(int row,int n) {
		for(int i=0;i<row;++i) {
			if(col[i]==col[row]||Math.abs(i-row)==Math.abs(col[i]-col[row])) {
				return false;
			}
		}
		return true;
	}
}

posted on   coding_gaga  阅读(135)  评论(0编辑  收藏  举报

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示