码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Solutions : N-Queens II

时间:2014-08-25 19:22:11      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:leetcode   java   algorithms   datastructure   dp   

Follow up for N-Queens problem.

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

bubuko.com,布布扣


Java Solutions( Refer to blog  http://blog.csdn.net/mbh_1991/article/details/23869459 and  http://blog.csdn.net/u011095253/article/details/9158473   ):

public class Solution {
	int count;
    public int totalNQueens(int n) {
        count=0;
		int[] location=new int[n];
		dfs(location,0,n);
		return count;
    }
	private void dfs(int[] location,int cur,int n){
		if(cur==n)
			count++;
		else{
			for(int i=0;i<n;i++){
				location[cur]=i;
				if(isValid(location,cur))
					dfs(location,cur+1,n);
			}
		}
	}
	private boolean isValid(int[] location,int cur){
		for(int i=0;i<cur;i++){
			if(location[i]==location[cur]||Math.abs(location[i]-location[cur])==cur-i)
				return false;
		}
		return true;
	}
}

LeetCode Solutions : N-Queens II

标签:leetcode   java   algorithms   datastructure   dp   

原文地址:http://blog.csdn.net/lviiii/article/details/38823873

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!