51. N皇后

分析:

代码实现:

cpp 复制代码
/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */

bool isValid(char **res, int row, int col, int n) {
    // 检查列
    for (int i = 0; i < row; i++) {
        if (res[i][col] == 'Q') {
            return false;
        }
    }
    // 检查 45度角是否有皇后
    for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
        if (res[i][j] == 'Q') {
            return false;
        }
    }
    // 检查 135度角是否有皇后
    for(int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
        if (res[i][j] == 'Q') {
            return false;
        }
    }
    return true;
}

void DFS(char ***ans, int *returnSize, int **returnColumnSizes, char **res, int index, int n) { 
    // 枚举到最后一行,保存当前棋盘,因为如果不能成为皇后就不能进入下一行
    // 所以能到最后一行肯定是有效的
    if (index == n) {
        ans[(*returnSize)] = (char**)malloc(sizeof(char *) * n);
        for (int i = 0; i < n; i++) {
            ans[(*returnSize)][i] = (char*)malloc(sizeof(char) * (n + 1));
            strcpy(ans[(*returnSize)][i], res[i]);
        }
        (*returnColumnSizes)[(*returnSize)++] = n;
        return;
    }
    // 枚举当前行中每一个元素
    for (int i = 0; i < n; i++) {
        if (isValid(res, index, i, n) == true) { // 检查当前位置能不能放皇后
            res[index][i] = 'Q'; // 可以直接放皇后
            DFS(ans, returnSize, returnColumnSizes, res, index + 1, n); // 进入下一行,重复当前步骤
            res[index][i] = '.'; // 回溯,进行判断下一个元素
        }
    }
}

char ***solveNQueens(int n, int *returnSize, int **returnColumnSizes){
    char ***ans = (char***)malloc(sizeof(char**) * 1000);
    *returnColumnSizes = (int*)malloc(sizeof(int) * 1000);
    *returnSize = 0;
    char **res = (char**)malloc(sizeof(char *) * n);
    for (int i = 0; i < n; i++) { // 定义棋盘并初始化
        res[i] = (char*)malloc(sizeof(char) * (n + 1));
        memset(res[i], '.', sizeof(char) * n);
        res[i][n] = '\0';
    }
    // 递归枚举每一个位置
    DFS(ans, returnSize, returnColumnSizes, res, 0, n);

    return ans;
}
相关推荐
Swift社区1 小时前
Swift 解 LeetCode 321:拼接两个数组中的最大数,贪心 + 合并全解析
开发语言·leetcode·swift
无聊的小坏坏2 小时前
力扣 239 题:滑动窗口最大值的两种高效解法
c++·算法·leetcode
YuTaoShao2 小时前
【LeetCode 热题 100】206. 反转链表——(解法一)值翻转
算法·leetcode·链表
YuTaoShao2 小时前
【LeetCode 热题 100】142. 环形链表 II——快慢指针
java·算法·leetcode·链表
Zedthm3 小时前
LeetCode1004. 最大连续1的个数 III
java·算法·leetcode
YuTaoShao4 小时前
【LeetCode 热题 100】73. 矩阵置零——(解法一)空间复杂度 O(M + N)
算法·leetcode·矩阵
dying_man4 小时前
LeetCode--42.接雨水
算法·leetcode
黑听人6 小时前
【力扣 困难 C】115. 不同的子序列
c语言·leetcode
前端拿破轮8 小时前
🤡🤡🤡面试官:就你这还每天刷leetcode?连四数相加和四数之和都分不清!
算法·leetcode·面试
无聊的小坏坏10 小时前
单调栈通关指南:从力扣 84 到力扣 42
c++·算法·leetcode