52. N-Queens II(dfs)

来源:互联网 发布:广告公司做图软件 编辑:程序博客网 时间:2024/06/18 15:11

题目:

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

Subscribe to see which companies asked this question

返回N皇后个数,和上题一样。

代码:

public class Solution {int total;    public int totalNQueens(int n) {        total = 0;        int[] p= new int[n];        dfs(p,0);        return total;    }    void dfs(int[] p,int row)    {    if(row== p.length)    {    total++;    }        for(int i=0;i<p.length;i++)    {    if(!isValid(p, row, i))continue;    p[row]=i;    dfs(p,row+1);    }    }        boolean isValid(int[] p,int row,int col)    {    for(int i=0;i<row;i++)    {    if(p[i]==col)return false;    if(Math.abs(i-row)==Math.abs(p[i]-col))return false;    }    return true;    }}


0 0
原创粉丝点击