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:

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:
c 复制代码
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);
}
相关推荐
Tairitsu_H29 分钟前
[LC优选算法#18] 前缀和 | 除⾃⾝以外数组的乘积 | 和为K的⼦数组 | 和可被K整除的⼦数组
算法·前缀和·哈希算法
凯瑟琳.奥古斯特1 小时前
力扣1008:前序重建BST
开发语言·c++·算法·leetcode·职场和发展
aqiu1111112 小时前
【算法日记 13】LeetCode 49. 字母异位词分组:哈希表的进阶“降维打击”
算法·leetcode·散列表
KaMeidebaby2 小时前
卡梅德生物技术快报|纳米抗体技术全套实操流程:AFB1 全合成文库淘选 + 分子对接定点突变参数手册
人工智能·python·tcp/ip·算法·机器学习
巴糖2 小时前
从做早餐理解 DAG 与拓扑排序:任务依赖图的核心逻辑
算法
2601_962851743 小时前
计算机毕业设计之基于YOLOV10的低光照目标检测算法研究与实现
大数据·算法·yolo·目标检测·信息可视化·cnn·课程设计
Darkwanderor3 小时前
Linux进程优先级操作
linux·运维·c语言·c++
magicwt3 小时前
快手自动出价论文GAVE阅读笔记
算法
智者知已应修善业3 小时前
【P12159蓝桥杯数组翻转】2025-4-24
c语言·c++·经验分享·笔记·算法·蓝桥杯
SuperByteMaster3 小时前
keil link misc controls
c语言