一 题目
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.