//用双重指针来 char (*queen)[n] 实现可能更方便一些
/*
按照国际象棋的规则,皇后可以攻击与之处在同一行或同一列或同一斜线上的棋子。
n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
给你一个整数 n ,返回所有不同的 n 皇后问题 的解决方案。
每一种解法包含一个不同的 n 皇后问题 的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/n-queens
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
输入:n = 4
输出:[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
解释:如上图所示,4 皇后问题存在两个不同的解法。
示例 2:
输入:n = 1
输出:[["Q"]]
提示:
1 <= n <= 9
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
/**
* 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().
*/
#define QUEEN 'Q'
#define EMPTY '.'
static bool can_fill(int *filled_pos, int i, int j, int n)
{
for (int k = 0; k < i; k++) {
if (((i - k) == abs(j - filled_pos[k])) || (j == filled_pos[k])) {
return false;
}
}
return true;
}
static char **fill_all(int *filled_pos, int n)
{
char **queen = (char **)malloc(sizeof(char *) * n);
for(int i = 0; i < n; i++) {
char *tmp = (char *)malloc(sizeof(char) * (n + 1));
memset(tmp, EMPTY, sizeof(char) * n);
tmp[filled_pos[i]] = QUEEN;
tmp[n] = '\0';
queen[i] = tmp;
}
return (char **)queen;
}
char *** solveNQueens(int n, int* returnSize, int** returnColumnSizes)
{
int i, j, count = 0;
char ***out = (char ***)malloc(sizeof(char **) * n * n * n);
int *filled_pos = (int *)malloc(sizeof(int) * n);
filled_pos[0] = 0;
i = 1;
j = 0;
while (i < n) {
//for i row can't fill any one, go back to i-1 row
if (j > (n-1)) {
i--;
j = filled_pos[i] + 1;
if ((i == 0) && (j == n)) { //quit from go back
break;
} else if (i == 0) {
filled_pos[0] = j;
i = 1;
j = 0;
}
continue;
}
if (can_fill(filled_pos, i, j, n)) {
filled_pos[i] = j;
if ((i+1) == n) {
//got one solution, output it, then go back;
out[count++] = fill_all(filled_pos, n);
//go back
i--;
j = filled_pos[i] + 1;
} else {
i++;
j = 0;
}
} else {
j++;
}
}
if (n == 1) {
out[count++] = fill_all(filled_pos, n);
}
free(filled_pos);
*returnSize = count;
// actually, not need this param : returnColumnSizes = NULL;
*returnColumnSizes = (int*)malloc(count * sizeof(int));
for (i = 0; i < count; i++) {
(*returnColumnSizes)[i] = n;
}
return out;
}
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("please input queen number!\n");
return 0;
}
int return_size = 0;
int *returnColumnSizes = NULL;
int n = atoi(argv[1]);
char *** out = solveNQueens(n, &return_size, &returnColumnSizes);
for (int i = 0; i < return_size; i++) {
char **queen = (char **)out[i];
for (int j = 0; j < n; j++) {
printf("%s", queen[j]);
printf("\n");
free(queen[j]);
}
printf("\n\n");
}
printf("total queens: %d\n", return_size);
free(out);
free(returnColumnSizes);
return 0;
}
12-20
01-15
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交