51.N皇后

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值