129_leetcode_N-Queens

155 篇文章 0 订阅
155 篇文章 0 订阅

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

1:注意特殊情况;2:采用递归的方法,当遍历的时候满足题意,获取此时皇后的摆放位置;3:保存每一行放置皇后的位置;递归+回朔的方法 4:注意当前摆放位置不满足题意的条件

    vector<vector<string> > solveNQueens(int n)
    {
        vector<vector<string> > result;
        if( n <= 0 )
        {
            return result;
        }
        
        vector<string> tmpSolve;
        vector<int> pos(n, 0);
        
        for(int i = 0; i < n; i++)
        {
            pos[0] = i;
            solveNQueensCore(n, 1, result, pos);
        }
        
        return result;
    }
    
    void solveNQueensCore(int n, int curIndex, vector<vector<string> > &result, vector<int> &pos)
    {
        if(curIndex == n)
        {
            vector<string> tmpResult;
            for(int i = 0; i < n; i++)
            {
                string tmp = "";
                for(int j = 0; j < n; j++)
                {
                    if(j == pos[i])
                    {
                        tmp.push_back('Q');
                    }
                    else
                    {
                        tmp.push_back('.');
                    }
                }
                tmpResult.push_back(tmp);
            }
            result.push_back(tmpResult);
            return;
        }
        
        for(int i = 0; i < n; i++)
        {
            pos[curIndex] = i;
            if(check(pos, curIndex))
            {
                solveNQueensCore(n, curIndex + 1, result, pos);
            }
        }
    }
    
    bool check(vector<int> &pos, int curIndex)
    {
        for(int i = 0; i < curIndex; i++)
        {
            if(pos[i] == pos[curIndex] || pos[i] - pos[curIndex] == i - curIndex || pos[i] - pos[curIndex] == curIndex - i)
            {
                return false;
            }
        }
        return true;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值