[leetcode]N-Queens II

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]N-Queens II相关的知识,希望对你有一定的参考价值。

问题描写叙述:

Follow up for N-Queens problem.

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

技术分享

(N-Queens problem can see here )

基本思路:

可參照N-Queens问题。依照N-Queens 问题稍作改动就可以。


代码:

public class Solution {  //java
        public int result;
	    public boolean check_pos(int index, int loop, int [] record){

            for(int i = 0; i < index; i++){
                if(record[i] == loop)
                    return false ;
                if(record[i]+i == index + loop)
                	return false ;
                if(record[i] -loop == i - index )
                	return false ;
            }  
	        return true;
	    }
	    
	    public void  subNQueen(int [] record,int index, int n){
	    	if(index == n){
                result++;	    	    
	    	}
	    	
		    for(int loop = 1; loop <=n; loop++){
		    	if(check_pos(index, loop, record)){
		    		record[index] = loop;
			        subNQueen(record,index+1,n);
			        record[index] = 0;
		    	}
		    }
	    
	    }
    public int totalNQueens(int n) {
        int index = 0;
	    int [] record = new int[n];
	    subNQueen(record,0,n);
	    return result;
    }
}






以上是关于[leetcode]N-Queens II的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode][Java] N-Queens II

LeetCode52 N-Queens II

一天一道LeetCode#52. N-Queens II

Leetcode 52 N-Queens II 回溯搜索

leetcode - N-Queens II

Leetcode52 N-Queens II