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

    称号:给定一个整数n。这表明董事会的规模n*n。放置在电路板n皇后。在同一行上的要求,同一列,用对角线不能具有相同的大号,确定可行的解决方案的数量

    算法:深度优先搜索 + 修剪优化

    修剪优化方案,如以下(取4女王案例):

    不难发现存在下列规律:

    同一条左对角线:row - col + n = 恒定值
    同一条右对角线:row + col = 恒定值

    public class Solution {
        final int CHECK_NUMBER = 3;  // check tree points: col, left diagonal and right diagonal
    	    final int MAX_NUMBER = 1024;
    	    
    	    int nSolutions = 0;
    		boolean[][] isVisited = new boolean[CHECK_NUMBER][MAX_NUMBER];
    		
    		public int totalNQueens(int n) {
    	        for (int i=0; i<CHECK_NUMBER; ++i) {
    	        	isVisited[i] = new boolean[MAX_NUMBER];
    	        }
    	        
    	        dfs(0, n);
    	        return nSolutions;
    	    }
    		
    		/**
    		 * boolean[0][MAXN]:
    		 *
    		 * 0: check the col
    		 * 1: check the left diagonal
    		 * 2. check the right diagonal
    		 * 
    		 */
    		public void dfs(int row, int nGirds) {
    			if (row == nGirds) {
    				++nSolutions;
    				return ;
    			}
    			
    			for (int col=0; col<nGirds; ++col) {
    				if (!isVisited[0][col] 
    				 && !isVisited[1][row-col+nGirds]
    				 && !isVisited[2][row+col]) {
    					isVisited[0][col] = true;
    					isVisited[1][row-col+nGirds] = true;
    					isVisited[2][row+col] = true;
    					dfs(row+1, nGirds);
    					isVisited[0][col] = false;
    					isVisited[1][row-col+nGirds] = false;
    					isVisited[2][row+col] = false;
    				}
    			}
    		}
    }

    版权声明:本文博客原创文章。博客,未经同意,不得转载。

  • 相关阅读:
    GNU make manual 翻译(九十九)
    GNU make manual 翻译( 九十五)
    Shell的 for 循环小例子
    makefile中对目录遍历的小例子
    GNU make manual 翻译(九十三)
    GNU make manual 翻译( 一百)
    GNU make manual 翻译( 九十七)
    GNU make manual 翻译( 九十八)
    mapserver4.8.3 的readme.win32的中文翻译文件
    遥控器编程
  • 原文地址:https://www.cnblogs.com/blfshiye/p/4641996.html
Copyright © 2011-2022 走看看