[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;
    }
}

猜你喜欢

转载自www.cnblogs.com/coding-gaga/p/10946413.html