34.N-Queens II-N皇后问题 II(中等题)

来源:互联网 发布:手机声音扩大软件 编辑:程序博客网 时间:2024/06/05 10:13

N皇后问题 II

  1. 题目

    根据n皇后问题,现在返回n皇后不同的解决方案的数量而不是具体的放置布局。

  2. 样例

    比如n=4,存在2种解决方案

  3. 题解

参看33.N-Queens-N皇后问题(中等题)

class Solution {    /**     * Calculate the total number of distinct N-Queen solutions.     * @param n: The number of queens.     * @return: The total number of distinct solutions.     */    public int totalNQueens(int n) {        return getQueens(0,new int[n],n,0);    }    private int getQueens(int count,int[] row,int n,int index)    {        if (index == n)        {            return ++count;        }        for (int i=0; i<n;i++)        {            if (isValid(row,index,i))            {                row[index] = i;                count = getQueens(count,row,n,index+1);                row[index] = 0;            }        }        return count;    }    private boolean isValid(int[] row, int rowIndex, int columnIndex)    {        for (int i=0;i<rowIndex;i++)        {            if (row[i] == columnIndex ||  (Math.abs(row[i] - columnIndex) == Math.abs(i - rowIndex)) )            {                return false;            }        }        return true;    }};

Last Update 2016.9.27

0 0