leetcode 52. N-Queens II

一 题目

  The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return the number of distinct solutions to the n-queens puzzle.

Example:

Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

二  分析

hard 级别,还是跟上个题目leetcode 51. N-Queens 一样的,但是这个更简单些,只输出个数,不求具体的位置。

稍微改一下上个题的方式,返回结果改为全局的计数变量。

 static int res ;
	 public static int totalNQueens(int n) {
	        res =0;
	        int[] queens = new int[n];
			 //初始化-1
			 for(int i=0;i<n;i++){
				 queens[i] =-1;
			 }
			 helper(0,queens);
			 return res;
	    }
	
		
		private static void helper(int row, int[] queens) {
			//符合条件,放满了
			if(row== queens.length ){
				++res;
			}
			//遍历所有列		
			for(int col=0;col<queens.length;col++ ){
				//check:是否可在row行j列处放Q,不满足就尝试下一列
				if(isValid(queens ,row,col)){
					queens[row]= col;
					helper(row+1,queens);
					queens[row]= -1;
				}
			}
			
		}
		//判断当前位置能否放Q
		static boolean isValid(int[] queens, int row,int col ){
			
			for(int i=0;i<row;i++){
				//check 列
				if(queens[i]==col){
					return false;
				}
				//判断对角线:横坐标差的绝对值等于纵坐标差的绝对值
				if (Math.abs(i - row) == Math.abs(queens[i] - col)) return false;
			}	
			
			return true;
		}

 

Runtime: 2 ms, faster than 55.53% of Java online submissions for N-Queens II.

Memory Usage: 32.7 MB, less than 13.04% of Java online submissions for N-Queens II.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值