Leetcode -- N-Queens

来源:互联网 发布:淘宝买家贷款5万怎么贷 编辑:程序博客网 时间:2024/05/01 19:21

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>> res;    bool check(vector<int> pos,int cur,int p)    {        for(int i=0;i<cur;++i)            if(pos[i]==p||abs(pos[i]-p)==abs(i-cur)) return 0;        return 1;    }    void fun(vector<int> pos,int r)    {        int n=pos.size();        if(r==n)        {            vector<string> cur(n,string(n,'.'));            for(int i=0;i<n;++i)                cur[i][pos[i]]='Q';            res.push_back(cur);            return;        }        for(int j=0;j<n;++j)        {            if(check(pos,r,j))            {                pos[r]=j;                fun(pos,r+1);            }        }    }    vector<vector<string>> solveNQueens(int n) {        vector<int> pos(n,0);        fun(pos,0);        return res;    }};


0 0
原创粉丝点击