LeetCode 52. N-Queens II(N皇后问题之 II)

222 阅读1分钟

leetcode.com/problems/n-…

The n-queens puzzle is the problem of placing n queens on an n x 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 1:

Input: n = 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown.

Example 2:

Input: n = 1
Output: 1

 

Constraints:

  • 1 <= n <= 9

解法一:

这道题跟 LeetCode 51. N-Queens(N皇后问题)解题思路是一样的,不同的是我们不需要记录皇后所在的位置,只需要把总摆法数返回即可。

class Solution {
    fun totalNQueens(n: Int): Int {
        var result : Int = 0
        val cols = mutableSetOf<Int>()
        val pie  = mutableSetOf<Int>()
        val na = mutableSetOf<Int>()
        result = dfs(n,0,cols,pie,na,0)
        return result
    }

    fun dfs(n : Int, level:Int, cols:MutableSet<Int>, pie:MutableSet<Int>,
            na:MutableSet<Int>, count: Int):Int{
        var currentCount = count
        if (level>=n){
            return currentCount+1
        }else{
            for (col in 0 until n){
                if (!cols.contains(col)&&!pie.contains(level+col)&&
                    !na.contains(level-col)){
                    cols.add(col)
                    pie.add(level+col)
                    na.add(level-col)
                    currentCount = dfs(n,level+1,cols,pie,na,currentCount)
                    cols.remove(col)
                    pie.remove(level+col)
                    na.remove(level-col)
                }
            }
        }
        return currentCount
    }
}