51. N-Queens

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.."]
]
class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        std::vector<std::vector<std::string> > result;
        std::vector<std::vector<int> > mark;
        std::vector<std::string> location;
        
        for(int i=0; i<n; i++)
        {
            mark.push_back((std::vector<int>()));
            for(int j=0; j<n; j++)
            {
                mark[i].push_back(0);                  
            }
            location.push_back("");
            location[i].append(n,'.');
        }
        generate(0, n, location, result, mark);
        return result;
    }
private:
    void put_down_the_queen(int x, int y, std::vector<std::vector<int> > &mark)
    {
        static const int dx[] = {-1, 1, 0, 0, -1, -1, 1, 1};
        static const int dy[] = {0, 0, -1, 1, -1, 1, -1, 1};
        
        mark[x][y]=1;
        for(int i=1; i<mark.size(); i++)
        {
            for(int j=0; j<8; j++)
            {
                int new_x = x+i*dx[j];
                int new_y = y+i*dy[j];
                if(new_x>=0&&new_x<mark.size()&&new_y>=0&&new_y<mark.size())
                {
                    mark[new_x][new_y] = 1;
                }
            }
        }
    }
    void generate(int k, int n, std::vector<std::string> &location, std::vector<std::vector<std::string> > &result,
                 std::vector<std::vector<int> > &mark)
    {
        if(k==n)
        {
            result.push_back(location);
            return;
        }
        for(int i=0; i<n; i++)
        {
            if(mark[k][i]==0){
                std::vector<std::vector<int> > tmp_mark = mark;
                location[k][i]='Q';
                put_down_the_queen(k, i, mark);
                generate(k+1, n, location, result, mark);
                mark = tmp_mark;
                location[k][i] = '.';
            }
        }
    }
                           
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值