Wuyi N-queens.
The n-queens Puzzle is the problem of placing N Queens on a nxn chessboard such that No, Queens attack.
650) this.width=650; "src=" Http://www.leetcode.com/wp-content/uploads/2012/03/8-queens.png "style=" border:0px; Vertical-align:middle; "alt=" 8-queens.png "/>
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-distinct solutions to the 4-queens puzzle:
[ [". Q.. ",//solution 1" ... Q "," Q ... ",".. Q. "], ["]. Q. ",//Solution 2" Q ... "," ... Q ",". Q.. "]
Main topic:
Given a n*n board, put n Q in the chessboard, require each row, each column has only one q, and the diagonal of each Q can only have one Q.
Ideas:
This is a typical backtracking problem . A road to the black, went to the black to return to a step, and then go, until a road to walk. Return to continue looking for other way out.
There are several key points that need to be addressed to solve this problem:
1. Selection of data structures to preserve a viable route
When you save a workable route, select a 2-d array when selecting a data structure or what you need to use your head, and finally measure, select a one-dimensional array.
For example, a legal route for 4-queue
[". Q.. ",//solution 1" ... Q "," Q ... ",".. Q. "],
Then it corresponds to a 1-bit array of {1,3,0,2}
Explain:
1 is the No. 0 bit of the array, corresponding to the No. 0 row of the two-dimensional array, the corresponding value is 1, indicating that in the No. 0 row, the 1th column can be put Q.
3 is the 1th bit of the array, corresponding to the 1th row of the two-dimensional array, the corresponding value is 3, indicating that in the 1th row, the 3rd column can be put Q.
0 is the 2nd bit of the array, corresponding to the 3rd row of the two-dimensional array, the corresponding value is 0, indicating that in the 2nd row, the No. 0 column can be put Q.
2 is the 3rd bit of the array, corresponding to the 3rd row of the two-dimensional array, the corresponding value is 2, indicating that in the 3rd row, the 2nd column can be put Q.
The array's subscript is the row, and the element value of the array is the column. The position of Q is determined by the row and column.
2. How to determine if the element to be added is legal
To insert a legal element into a legal position, you need to determine whether it is legal, where a function is used
BOOL IsValid (int curindex, int val, int n, vector<int> &a)
Curindex represents the subscript, or row, of the element currently being inserted in the legal array. Val is the column value to insert. n is the number of queue,a that is an array that holds the temporary legal route.
Judge A[i] = = Val equal indicates that the column repeats.
The slope of the diagonal is 1 or-1, so if |val-a[i]| /|cur-i| = = 1, then the description is on the same diagonal.
3. Place the legal path one at a to put in the result temporary array. Converts the resulting temporary array into an array of results.
The code is as follows:
class solution {public: //determine the current value to be inserted Val in this position curindex is legal bool isvalid (int curindex, int val ,int n, vector<int> &a) { if (curindex < n ) { for (int i = curindex - 1; i > = 0; --i) { if (a[i] == val)// Determine if there is a duplicate return false; } for on the column (int i = curindex - 1; i >= 0; --i) { if (ABS (val - a[i) == (curindex - i))//Judging whether there are duplicates on the slash { return false; } } return true; } return false; } void putqueens (Int val &NBSP;,&NBSP;VECTOR<INT>&NBSP;&A)//Put a valid value into the current temporary result array { A.push_back (val); } //start the number of rows started, that is, the placement of the first start+1 queue void solvenqueenstointvector (int start,int n, vector<int> &cur, vector<vector<int>> &result)//convert int to handle { if (Cur.size () == n) { result.push_back (cur); return; } if (start == n) return; //Typical backtracking routines for (int i = 0; i < n; i++) { if (!isvalid (Cur.size (), i, n, cur) continue; vector<int> temp (cur);//Save Vector putqueens before Change (i, cur ); solvenqueenstointvector (Start + 1, n, cur, result); cur.swap (temp); } } vector<vector<string>> solvenqueens (int n) { vector<int> cur; vector<vector <int>> tempResult; vector<vector<string>> result; solvenqueenstointvector (0,n,cur,tempresult); Vector<vector<int>> tempResult convert to target result result for (int i = 0; i < tempresult.size (); i++) { vector<string> floorVector; string floor; for (Int j = 0; j < tempresult[i].size (); j++) { for (int k = 0; k < tempresult[i][j]; k++) { floor += "."; } floor += "Q"; for (int k = tempresult[i][j] + 1; k < n ; k++) { floor += "."; } floorvector.push_back (fLoor); floor.clear (); } result.push_back ( Floorvector); floorvector.clear (); } return result; }};
Summary:
The problem of backtracking is evident in the n-queue question.
Thinking of solving problems by backtracking
(1) To define the solution space for the problem;
(2) Determine the spatial structure of the solution that is easy to search;
(3) Searching the solution space in depth first, and using pruning function to avoid invalid search during the searching process.
Backtracking is to let the computer automatically to search, meet the situation to end or save, in a path to the end can not find the solution, go back to the original fork, choose a road that has not traveled before to continue probing until the solution or go through all the path. On this point, backtracking and so-called DFS (Depth-first search) are the same. Now the key is, how to implement the search? Since backtracking is generally implemented using recursion, how does that recursive call go about? My understanding is, first of all, to determine whether this test is valid, if valid, add this element, and then proceed to the next recursive, recursive after the return to the legal element before the state, the next cycle, if not valid directly to the next cycle.
2016-08-15 15:53:37
This article is from the "Do Your best" blog, so be sure to keep this source http://qiaopeng688.blog.51cto.com/3572484/1838480
Leetcode 51. N-queens | Backtracking questions (n Queen's question) | Hard