Leetcode first brush _ N-Queens

Source: Internet
Author: User

The eight queens question should be a model of backtracking teaching. When I was a bachelor, I had a course called object-oriented. The last appendix had the source code for this problem. I didn't know programming at the time. I was very happy to copy it and run it.

The Queen's restriction is that they cannot be in the same column or diagonal line. Obviously, each column must have a queen. You only need to use a one-dimensional array to record the Queen's position on each row. The idea of the algorithm is: from the first line, try to put the Queen on a column, you can use a vis array to save the columns with the queen, when I find a column with no queen, I try to put the current queen, and then see if there is any former queen with this queen with the same diagonal line, if the same diagonal line, you can only try the following position. After trying all the positions, it indicates that the position of the Queen in front is incorrect. It is necessary to enter the tracing link in the legend. During the Backtracking process, the row is to be returned to the previous line, which is no doubt, the key is where the row should start to continue. If recursion is used, don't worry. He will start from the next position of recursion. What about the loop? It should start from the next location allocated to him. At the same time, the column where he was located should be released.

There is another question about loop implementation. When will it be released? If you only need a group of solutions, you can find the solution, that is, after all the queens are restored, they will exit. However, if all solutions are generated, backtracing is required after a group of solutions is obtained. At first, I thought wrong about the backtracing in this case. I thought that I should move the queen of the first line to the next position, and there was a lot less solution. It is very likely that the first few queens do not need to be changed, but only the next few can be changed. Therefore, the backtracking in this case is exactly the same as the backtracking in case of failed attempts.

Then, the exit condition is used. Think about how it will go back to the end and reach the first line. The first line moves the queen to the next position of the current place. Therefore, when the first line tries all the columns, that is, when the next column exceeded the chessboard, it should be stopped.

class Solution {public:    vector<vector<string> > solveNQueens(int n) {        int pos[n];        vector<vector<string> > res;        if(n == 0)  return res;        vector<string> tpres;        memset(pos, 0, sizeof(pos));        int i=0, j=0, start=0;        bool flag, vis[n];        memset(vis, 0, sizeof(vis));        string line(n, '.'), tpline(n, '.');        while(i<n){            for(j=start;j<n;j++){                if(vis[j]) continue;                flag = true;                for(int k=0;k<i;k++){                    if(abs(k-i) == abs(pos[k] - j)){                        flag = false;                        break;                    }                }                if(!flag) continue;                pos[i] = j;                vis[j] = 1;                break;            }            if(j==n){                --i;                vis[pos[i]] = 0;                start = pos[i]+1;                if(i==0&&start>=n)  break;                continue;            }else{                i++;                start = 0;            }            if(i == n){                for(i=0;i<n;i++){                    line = tpline;                    line[pos[i]] = 'Q';                    tpres.push_back(line);                }                res.push_back(tpres);                tpres.clear();                --i;                vis[pos[i]] = 0;                start = pos[i]+1;                if(i==0&&start>=n) break;            }        }        return res;    }};

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.