zoukankan      html  css  js  c++  java
  • [LeetCode][Java] N-Queens II

    题目:

    Follow up for N-Queens problem.

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


    题意:

    接上题N-Queens problem,这里仅仅是要求返回全部的不同的解的数目。

    算法分析:

    思路与上题同样,代码比上题更加简洁了

    AC代码:

    <span style="font-size:12px;">public class Solution 
    {
        private int res=0;
        public int totalNQueens(int n) 
        {  
            int[] loc = new int[n];  //记录皇后处于哪一列,列数组
            dfs(loc,0,n);  
            return res;  
        }  
        public void dfs(int[] loc, int cur, int n)
        {  
            if(cur==n)   
                res++;  
            else
            {  
                for(int i=0;i<n;i++)
                {  
                    loc[cur] = i;  
                    if(isValid(loc,cur))  
                        dfs(loc,cur+1,n);  //再放皇后m+1, 假设皇后m+1放完并返回了  
                                              //两种可能:  1:冲突,返回了  2.一直将所有的皇后所有放完并安全返回了  
                                            //将皇后m回溯。探索新的可能或者安全的位置  --->
                }  
            }  
        }  
        public boolean isValid(int[] loc, int cur)
        {  
            for(int i=0;i<cur;i++)//仅仅须要保证与那些已经就位的皇后不冲突就可以  
            {  
                if(loc[i]==loc[cur]||Math.abs(loc[i]-loc[cur])==(cur-i)) //验证对角线,依据对角线性质,长 = 宽 
                                                                         //那么我们不难写出 Math.abs(loc[i] - loc[cur]) == (cur - i) 
                    return false;  
            }  
            return true;  
        }  
    
    }</span>


  • 相关阅读:
    send和sendmsg性能测试【sendmsg和send的性能基本一样,并没有得到优化】
    send和sendmsg性能测试
    SparkException: Master removed our application
    大数据入门:各种大数据技术介绍
    78 subsets
    C、C ++的内存模型
    将博客搬至CSDN
    适配器模式
    建造者(Builder)模式
    桥接模式
  • 原文地址:https://www.cnblogs.com/claireyuancy/p/6862901.html
Copyright © 2011-2022 走看看