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);
}
相关推荐
手写码匠几秒前
华为云Flexus+DeepSeek征文|华为云MaaS DeepSeek推理服务 × Flexus云服务器 × Dify一键部署:性能评测实战
人工智能·深度学习·算法·aigc
en.en..35 分钟前
C语言 static函数与头文件封装规范
java·c语言·前端
啥都想学点的研究生1 小时前
一篇文章讲清楚:逻辑回归
算法·机器学习·逻辑回归
布莱克6051 小时前
栈(Stack)详解:定义、作用、应用场景及与队列的区别(附 C/C++ 代码)
c语言·开发语言·c++·
wuyk5551 小时前
从零吃透 Modbus 通信|第 6 章:线圈功能码 05/0F 实现 & Modbus‑TCP 基础入门
c语言·网络·网络协议·tcp/ip
货拉拉技术2 小时前
Agent 场景下 Token 成本优化的实战技巧
算法
hahaha60162 小时前
HLS高层次综合设计技巧--循环merge和循环split
人工智能·算法·计算机视觉
JAI科研2 小时前
Deepseek Agent Harness教程(七) | Deepseek Harness不是一个内核加一堆插件
开发语言·人工智能·深度学习·算法·自然语言处理·transformer·vllm
集思广益的灰太狼2 小时前
变频器启动致PLC数据异常?西门子G120配合滤波器EMC抑制方案
人工智能·算法·工控·emc·电磁兼容·变频器·西门子
zbyyd2 小时前
Linux 进程间通信(IPC):信号、消息队列、共享内存与信号量详解
linux·运维·c语言