[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;
				}
			}
		}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值