LeetCode 52. N-Queens II(dfs)

题目来源:https://leetcode.com/problems/n-queens-ii/

问题描述

52. N-Queens II

Hard

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.."]
]

------------------------------------------------------------

题意

N皇后问题。在N×N的棋盘上放N个皇后,使得她们不会互相攻击。与LeetCode 51. N-Queens(dfs)不同的是,这题只要求满足条件的摆放的种数。

------------------------------------------------------------

思路

扫描二维码关注公众号,回复: 5964187 查看本文章

LeetCode 51. N-Queens(dfs)完全一样,就是dfs深搜。

------------------------------------------------------------

代码

class Solution {
    private int ans = 0;
    private int n;
    private int[] mask;
    private boolean[] col_mark;
    private boolean[] sub_mark;
    private boolean[] sum_mark;
    
    private void init(int n)
    {
        this.n = n;
        this.mask = new int[n];
        this.col_mark = new boolean[n];
        this.sub_mark = new boolean[2*n-1];
        this.sum_mark = new boolean[2*n-1];
    }
    
    public void dfs(int x)
    {
        if (x == n)
        {
            this.ans++;
            return;
        }
        int y = 0, bit = 1;
        for (y=0; y<this.n; y++)
        {
            if (!this.col_mark[y] && !this.sub_mark[x-y+n-1] && !this.sum_mark[x+y])
            {
                this.mask[x] = bit;
                this.col_mark[y] = true;
                this.sub_mark[x-y+n-1] = true;
                this.sum_mark[x+y] = true;
                dfs(x+1);
                this.col_mark[y] = false;
                this.sub_mark[x-y+n-1] = false;
                this.sum_mark[x+y] = false;
            }
            bit <<= 1;
        }
    }
    
    public int totalNQueens(int n) {
        if (n == 0)
        {
            return 1;
        }
        init(n);
        dfs(0);
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/da_kao_la/article/details/89215301
今日推荐