数据结构 C 代码 6.3: N 后问题

本文介绍了N皇后问题的解决方案,通过递归的回溯算法寻找合法的棋盘布局,展示了如何使用C语言代码实现,并提供了运行结果和代码分析。重点在于理解回溯法在解决此类问题中的应用和核心原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

摘要: N 后问题说明, 一山不容二只母老虎.

1. 代码

先上代码, 再说废话.

#include <stdio.h>
#include <malloc.h>
#include <math.h>
#include <stdbool.h>
#include <stdlib.h>

/**
 * Place it there, applicable?
 */
bool place(int* paraSolution, int paraT){
	int j;
    for (j = 1; j < paraT; j ++){
        if ((abs(paraT - j) == abs(paraSolution[j] - paraSolution[paraT])) || (paraSolution[j] == paraSolution[paraT]))
            return false;
    }//Of for
    return true;
}//Of place

/**
 * Backtracking.
 */
void backtracking(int* paraSolution, int paraN, int paraT){
	int i;
    if (paraT > paraN){
        for (i = 1; i <= paraN; i ++)
            printf("%d ", paraSolution[i]);
		printf("\r\n");
    }else{
        for (i = 1; i <= paraN; i ++){
            paraSolution[paraT] = i;
            if (place(paraSolution, paraT))
                backtracking(paraSolution, paraN, paraT + 1);
        }//Of for i
    }//Of if
}//Of backtracking

/**
 * Title: n queens.<br>
 */
void nQueen(int paraN){
	int i;
	int* solution = (int*)malloc((paraN + 1) * sizeof(int));
	for (i = 0; i <= paraN; i ++)
		solution[i] = 0;

    backtracking(solution, paraN, 1);
}//Of nQueen

/**
 * The entrance.
 */
int main(){
	nQueen(5);
	return 1;
}//Of main

2. 运行结果

1 3 5 2 4
1 4 2 5 3
2 4 1 3 5
2 5 3 1 4
3 1 4 2 5
3 5 2 4 1
4 1 3 5 2
4 2 5 3 1
5 2 4 1 3
5 3 1 4 2
Press any key to continue

3. 代码分析

  • 回溯算法是万能解题法.
    • 应对组合优化问题.
  • 回溯法的框架都是一致的.
    • 本问题的解空间: n+1n + 1n+1nnn 叉树.
    • 类似于汉诺塔问题, 这里并没有显示地构建树.
    • 深度优先遍历 + 剪枝技术.
    • 空间复杂度 O(n)O(n)O(n). 时间复杂度未知.

4. DeepSeek 修订版

#include <stdio.h>
#include <stdlib.h>  // 包含malloc/free的标准头文件
#include <stdbool.h>

#define MAX_QUEENS 20  // 最大支持皇后数

/**
 * @brief 检查当前位置是否合法
 * @param queen_pos 皇后位置数组(1-based索引)
 * @param current_row 当前要检查的行号
 * @return bool 是否合法位置
 */
bool is_valid_position(const int queen_pos[], int current_row) {
    for (int prev_row = 1; prev_row < current_row; ++prev_row) {
        const int col_diff = abs(queen_pos[prev_row] - queen_pos[current_row]);
        const int row_diff = current_row - prev_row;
        
        // 检查同一列或对角线冲突
        if (col_diff == 0 || col_diff == row_diff) {
            return false;
        }
    }
    return true;
}

/**
 * @brief 递归求解N皇后问题
 * @param queen_pos 皇后位置数组(1-based索引)
 * @param n_queens 皇后总数
 * @param current_row 当前处理的行号
 */
void solve_n_queens_helper(int queen_pos[], int n_queens, int current_row) {
    if (current_row > n_queens) {
        // 打印解决方案
        for (int i = 1; i <= n_queens; ++i) {
            printf("%d ", queen_pos[i]);
        }
        putchar('\n');
        return;
    }

    // 尝试当前行的每一列
    for (int col = 1; col <= n_queens; ++col) {
        queen_pos[current_row] = col;
        if (is_valid_position(queen_pos, current_row)) {
            solve_n_queens_helper(queen_pos, n_queens, current_row + 1);
        }
    }
}

/**
 * @brief 求解N皇后问题入口函数
 * @param n_queens 皇后数量
 */
void solve_n_queens(int n_queens) {
    if (n_queens < 1 || n_queens > MAX_QUEENS) {
        fprintf(stderr, "Error: Invalid number of queens (1-%d)\n", MAX_QUEENS);
        return;
    }

    // 分配存储空间(1-based索引,0号元素未使用)
    int *queen_pos = (int*)malloc((n_queens + 1) * sizeof(int));
    if (!queen_pos) {
        perror("Memory allocation failed");
        return;
    }

    // 初始化数组
    for (int i = 0; i <= n_queens; ++i) {
        queen_pos[i] = 0;
    }

    solve_n_queens_helper(queen_pos, n_queens, 1);
    free(queen_pos);  // 释放内存
}

/**
 * @brief 主函数
 */
int main() {
    printf("Solutions for n-Queens problem:\n");
    solve_n_queens(5);
    return 0;  // 正确返回状态码
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值