n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
给你一个整数 n ,返回所有不同的 n 皇后问题 的解决方案。
每一种解法包含一个不同的 n 皇后问题 的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/n-queens
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* 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().
*/
int count;
int hash[9][9];
char output[9][9];
void doAdd(int r,int c,int n,int val)
{
if(r<0||r>=n)return;
if(c<0||c>=n)return;
hash[r][c] += val;
}
void add(int r,int c,int n,int val)
{
for(int i=0;i<n;i++)
{
doAdd(r,c+i,n,val);
doAdd(r+i,c,n,val);
doAdd(r+i,c+i,n,val);
doAdd(r-i,c-i,n,val);
doAdd(r-i,c+i,n,val);
doAdd(r+i,c-i,n,val);
}
}
void putChar(int r,int c,char ch)
{
output[r][c] = ch;
}
void dfs(char ***res,int depth,int maxDepth)
{
if(depth >= maxDepth)
{
res[count] = (char **)malloc(sizeof(char *)*maxDepth);
for(int i=0;i<maxDepth;i++)
{
res[count][i] = (char *)malloc(sizeof(char)*(maxDepth+1));
int j;
for(j=0;j<maxDepth;j++)
{
res[count][i][j] = output[i][j];
}
res[count][i][j] = '\0';
}
count++;
return;
}
for(int i=0;i<maxDepth;i++)
{
if(hash[depth][i] == 0)
{
add(depth,i,maxDepth,1);
putChar(depth,i,'Q');
dfs(res,depth+1,maxDepth);
putChar(depth,i,'.');
add(depth,i,maxDepth,-1);
}
}
}
char *** solveNQueens(int n, int* returnSize, int** returnColumnSizes){
count = 0;
memset(hash,0,sizeof(hash));
memset(output,'.',sizeof(output));
char ***res = (char ***)malloc(sizeof(char **)*500);
dfs(res,0,n);
*returnSize = count;
*returnColumnSizes = malloc(sizeof(int)*count);
for(int i=0;i<count;i++)
{
(*returnColumnSizes)[i] = n;
}
return res;
}