0052. N-Queens II (H)

N-Queens II (H)

题目

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

0052. N-Queens II (H)_第1张图片

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个皇后,使得每一行、每一列、每一条对角线有且只有一个皇后。统计所有有效的放置方法的个数。

思路

与 51. N-Queens 方法相同,但不需要记录每一种解法,只要求统计个数。

因为不需要记录组合,可以只需要三个数组来对当前位置进行判断:当前列是否被占用,当前左对角线(主对角线方向)是否被占用,当前右对角线(副对角线方向)是否被占用。通过画图寻找规律可得:共有(2n-1)条左对角线,且row-col+n-1相同(加上n-1是为了让值能从0开始)的坐标位于同一左对角线;共有(2n-1)条右对角线,且row+col相同的坐标位于同一右对角线。


代码实现

Java

记录组合

class Solution {
    int count = 0;
    
    public int totalNQueens(int n) {
        generate(0, new int[n], new boolean[n]);
        return count;
    }

    private void generate(int row, int[] queen, boolean[] occupied) {
        if (row == occupied.length) {
            count++;
            return;
        }

        for (int col = 0; col < occupied.length; col++) {
            if (!occupied[col]) {
                boolean isValid = true;
                for (int preRow = 0; preRow < row; preRow++) {
                    if (Math.abs(row - preRow) == Math.abs(queen[preRow] - col)) {
                        isValid = false;
                        break;
                    }
                }

                if (isValid) {
                    queen[row] = col;
                    occupied[col] = true;
                    generate(row + 1, queen, occupied);
                    occupied[col] = false;
                }
            }
        }
    }
}

不记录组合

class Solution {
    int count = 0;

    public int totalNQueens(int n) {
        generate(0, new boolean[2 * n - 1], new boolean[2 * n - 1], new boolean[n], n);
        return count;
    }

    private void generate(int row, boolean[] diaLeft, boolean[] diaRight, boolean[] colValid, int n) {
        if (row == n) {
            count++;
            return;
        }

        for (int col = 0; col < n; col++) {
            int dl = row - col + n - 1;
            int dr = row + col;
            if (!colValid[col] && !diaLeft[dl] && !diaRight[dr]) {
                colValid[col] = diaLeft[dl] = diaRight[dr] = true;
                generate(row + 1, diaLeft, diaRight, colValid, n);
                colValid[col] = diaLeft[dl] = diaRight[dr] = false;
            }
        }
    }
}

JavaScript

/**
 * @param {number} n
 * @return {number}
 */
var totalNQueens = function (n) {
  let board = new Array(n).fill(0).map((value, index) => index)
  return dfs(board, 0)
}

let dfs = function (board, index) {
  if (index === board.length) {
    return 1
  }

  let count = 0
  for (let i = index; i < board.length; i++) {
    let isValid = true
    for (let j = 0; j < index; j++) {
      if (index - j === Math.abs(board[j] - board[i])) {
        isValid = false
        break
      }
    }
    if (isValid) {
      [board[index], board[i]] = [board[i], board[index]]
      count += dfs(board, index + 1);
      [board[index], board[i]] = [board[i], board[index]]
    }
  }

  return count
}

你可能感兴趣的:(0052. N-Queens II (H))