首页 > 代码库 > LeetCode Solutions : N-Queens II
LeetCode Solutions : N-Queens II
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。