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;
}
相关推荐
一匹电信狗5 小时前
【LeetCode_547_990】并查集的应用——省份数量 + 等式方程的可满足性
c++·算法·leetcode·职场和发展·stl
鱼跃鹰飞6 小时前
Leetcode会员尊享100题:270.最接近的二叉树值
数据结构·算法·leetcode
We་ct7 小时前
LeetCode 205. 同构字符串:解题思路+代码优化全解析
前端·算法·leetcode·typescript
蒟蒻的贤10 小时前
leetcode链表
算法·leetcode·链表
执着25911 小时前
力扣hot100 - 94、二叉树的中序遍历
数据结构·算法·leetcode
老鼠只爱大米15 小时前
LeetCode经典算法面试题 #114:二叉树展开为链表(递归、迭代、Morris等多种实现方案详细解析)
算法·leetcode·二叉树·原地算法·morris遍历·二叉树展开
参.商.16 小时前
【Day25】26.删除有序数组中的重复项 80.删除有序数组中的重复项II
leetcode·golang
执着25916 小时前
力扣hot100 - 144、二叉树的前序遍历
数据结构·算法·leetcode
散峰而望16 小时前
【算法竞赛】树
java·数据结构·c++·算法·leetcode·贪心算法·推荐算法
Anastasiozzzz17 小时前
LeetCode hot100 45 跳跃游戏2
算法·leetcode·游戏