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;
}
相关推荐
_日拱一卒27 分钟前
LeetCode:46全排列
算法·leetcode·职场和发展
剑挑星河月40 分钟前
31.下一个排列
java·算法·leetcode
凌波粒43 分钟前
LeetCode--98.验证二叉搜索树(二叉树)
算法·leetcode·职场和发展
Misnearch1 小时前
3635. 最早完成陆地和水上游乐设施的时间II
leetcode·贪心·排序
WWW65261 小时前
代码随想录 打卡第四十七天
数据结构·算法·leetcode
smj2302_796826521 小时前
解决leetcode第3948题字典序最大的MEX数组
python·算法·leetcode
凌波粒2 小时前
LeetCode--530.二叉搜索树的最小绝对差(二叉树)
算法·leetcode·职场和发展
8Qi83 小时前
LeetCode 208:实现 Trie(前缀树)—— Java 题解 ✅
java·算法·leetcode·二叉树·tire树
罗超驿3 小时前
14.LeetCode 438 题解:滑动窗口+哈希表找所有字母异位词
java·算法·leetcode
小欣加油3 小时前
leetcode239 滑动窗口最大值
数据结构·c++·算法·leetcode·哈希算法