【LeetCode】N-Queens

来源:互联网 发布:mg2takemystyle 淘宝 编辑:程序博客网 时间:2024/06/11 04:58

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.."]]
思路:经典的n皇后问题,可以参考任何一本算法书。一般是通过回溯法求解。可以记录医用位置和下一次不能使用的左边位置和右边位置,得到可用的位置,然后遍历求出可用的位置,最后得到可用的结果。

class Solution {public:    vector<vector<string> > solveNQueens(int n) {        vector<vector<string> > res;        vector<string> tmp;        solveNQueensRe(n,0,0,0,res,tmp);        return res;    }    /*//主要参数列表:    n:个数    row:不可用的列位置    ld:不可用的左边位置    rd:不可用的右边位置*/    void solveNQueensRe(int n, int row, int ld, int rd, vector<vector<string> > &res,vector<string> &tmp){        //形成一次答案        if(row == (1<<n)-1){            res.push_back(tmp);            return;        }        int avail = ~(ld | row | rd);        //从第一个位置开始生成代码        for(int i = n-1;i>=0;--i){            //记录现在想要开始的位置            int pos = 1<<i;            //该位置可用            if(pos&avail){                string s(n,'.');                s[i]='Q';                tmp.push_back(s);                //                solveNQueensRe(n,row|pos,(ld|pos)<<1,(rd|pos)>>1,res,tmp);                tmp.pop_back();            }        }    }};




0 0
原创粉丝点击