zoukankan      html  css  js  c++  java
  • leetcode--N-Queens II

    Follow up for N-Queens problem.

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

     The idea is the same as that of Problem N-Queens problem : dfs

    public class Solution {
        public int totalNQueens(int n) {
           List<Integer> solution = new ArrayList<Integer>();
    		solution.add(0);
    		if(n == 1) return 1;
    		if(n >= 4){
    			List<Integer> position = new ArrayList<Integer>();
    			dfs(n, 0, position, solution);
    		}
    		return solution.get(0);
    	}
    	
    	private boolean dfs(int n, int row, List<Integer> position, List<Integer> solution){
    		if(row == n) return true;
    		for(int i = 0; i < n; ++i){
    			if(isValid(n, row * n + i, position)) {
    				position.add(row * n + i);
    				if(dfs(n, row + 1, position, solution))
    					solution.set(0, solution.get(0) + 1);
    				position.remove(row);
    			}
    		}
    		return false;
    	}
    	
    	private boolean isValid(int n, int k, List<Integer> position){
    		for(int i = 0; i < position.size(); ++i){
    			if((k % n  == position.get(i) % n) || Math.abs(k % n - position.get(i) % n) == (k / n - i))
    				return false;
    		}
    		return true;
        }
    }
    

      

  • 相关阅读:
    记录
    集合
    数据库一键退出脚本
    修改NLS_DATE_FORMAT的四种方式
    触发器
    (转)rlwrap真是一个好东西
    Windows常用技巧集锦
    UTL_FILE
    redis入门(03)redis的配置
    服务网关
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3825844.html
Copyright © 2011-2022 走看看