LeetCode //C - 52. N-Queens II

52. N-Queens II

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:

LeetCode //C - 52. N-Queens II_第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

From: LeetCode
Link: 52. N-Queens II


Solution:

Ideas:
  1. Start in the leftmost column.
  2. If all queens are placed, return true.
  3. Try all rows in the current column.
  • If the queen can be placed safely in this row, mark this cell and place the queen.
  • Recur to place the rest of the queens.
  • If placing the queen in the current row and proceeding to place the next queen leads to a solution, return true.
  • If placing the queen doesn’t lead to a solution, then unmark this cell, backtrack, and go to the next row in the current column.
  1. If all rows have been tried and none worked, return false to trigger backtracking.

To determine if a queen can be placed safely, we need to check three things:

  1. There’s no queen in the same row.
  2. There’s no queen in the same diagonal (both left upper diagonal and right upper diagonal).
Code:
bool isSafe(int board[], int row, int col, int n) {
    for (int i = 0; i < col; i++) {
        if (board[i] == row || 
            board[i] - i == row - col || 
            board[i] + i == row + col) {
            return false;
        }
    }
    return true;
}

int solveNQueensUtil(int n, int col, int board[]) {
    if (col >= n) {
        return 1;
    }
    int count = 0;
    for (int i = 0; i < n; i++) {
        if (isSafe(board, i, col, n)) {
            board[col] = i;
            count += solveNQueensUtil(n, col + 1, board);
        }
    }
    return count;
}

int totalNQueens(int n) {
    int board[n];
    for (int i = 0; i < n; i++) {
        board[i] = 0;
    }
    return solveNQueensUtil(n, 0, board);
}

你可能感兴趣的:(LeetCode,leetcode,c语言,算法)