[Leetcode] n-queens

Source: Internet
Author: User

N-queens

TheN-Queens puzzle is the problem of placingNQueens onN×NChessboard such that no two queens attack each other.

Given an integerN, Return all distinct solutions toN-Queens puzzle.

Each solution contains a distinct board configuration ofN-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.."]]

 

This is a routine with Sudoku solver. The Backtracking Method tries all possibilities and saves the feasible solution. You can compare them.

We first use vector <int> to store the feasible solution. The subscript represents the row number, and the element represents the column number.

Therefore, solution 1 is expressed as [1, 3,] using vector <int>.

The problem solving process is to try the number of columns in the next row (0 ~ N-1). If feasible, recursion is performed. If not, the pop-up will continue to try the next column.

A lot of comments are added to the Code, which is easy to understand.

class Solution {public:    vector<vector<string> > solveNQueens(int n)     {        vector<vector<int> > result;    //全局变量        vector<int> cur;                //递归栈中的变量        solve(result, cur, n);            //符合条件的cur加入result        return transfer(result, n);        //vector<int>转为vector<string>    }    void solve(vector<vector<int> > &result, vector<int> cur, int n)    {        if(cur.size() == n)        {//找到解            result.push_back(cur);        }        else        {            for(int i = 0; i < n; i ++)            {//尝试所有可能                cur.push_back(i);                if(isValid(cur))                {//可行则递归下去                    solve(result, cur, n);                }                cur.pop_back();            }        }    }    vector<vector<string> > transfer(vector<vector<int> > &result, int n)    {        vector<vector<string> > ret;        for(vector<vector<int> >::size_type st1 = 0; st1 < result.size(); st1 ++)        {//第st1个解            vector<string> cur(n, string(n,‘.‘));            for(vector<int>::size_type st2 = 0; st2 < n; st2 ++)            {//第st2行                cur[st2][result[st1][st2]] = ‘Q‘;            }            ret.push_back(cur);        }        return ret;    }    bool isValid(vector<int> &cur)    {//针对新加点进行验证        int sz = cur.size();        int row = sz-1;            //新加点的行数sz-1        int col = cur[sz-1];    //列数cur[sz-1]        for(vector<int>::size_type st = 0; st < sz-1; st ++)        {    //验证同列错误(由于数组下标不同,同行错误不存在)            if(col == cur[st])                return false;            //验证同对角线错误            if(fabs((double)row-st)==fabs((double)col-cur[st]))                return false;        }        return true;    }};

 

[Leetcode] n-queens

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.