8 Queen's question-backtracking (recursive)

Source: Internet
Author: User

N Queen's question


Description of the problem:
The N Queen question is a classic question, placing n queens on a n*n board, one per line and making it impossible to attack each other (the Queen on the same line, in the same column, on the same slash) will attack itself.


1. Because each piece is impossible to walk along. So it's understandable to take a pawn from every line of the board.
2. Because each row of pieces is not the same, so no same number can be in a column
3. Synthesis 1, 2. The problem is converted to [0-7] do a full arrangement, then meet no two numbers in the same slash
4. According to the slope formula (X1-X2)/(Y1-y2), so the combination of the same line is discharged according to this condition
5. The remaining combination is the column position, index, or line number of each piece.


var MAX = 8;var Ann = function A (arr) {if (arr.length = = 1) {return arr;} var rr = new Array (), for (var i = 0; i<arr.length;i++) {//get a copyvar ar = new Array (), for (var j = 0; J < arr.length ; j + +) {Ar[j] = arr[j];} Assume Ivar current = Ar[i];ar.splice (i,1), var childret = A (AR), for (var k = 0; k < childret.length;k++) {var str = (cu Rrent + "," + childret[k]); if (str.length! = 2 * MAX-1 | |!sameline (str)) {Rr.push (str)}}} return RR;} var Initarr = new Array (), for (var i = 0;i < MAX; i++) {Initarr.push (i);} var ret = Ann (Initarr); for (var i = 0;i < ret.length;i++) {Outret (ret[i]);} var count = 0;function Outret (r) {count = count + 1;console.log ("==============" + "," + count.tostring ()); var a = R.split (', '); for (var i = 0;i < Max; i++) {var aa = new Array (); for (var j = 0;j < Max; J + +) {aa.push (0);} Aa[a[i]] = 1;console.log (AA);}} function Sameline (str) {var arr = str.split (', '); for (var i = 0;i < Arr.length; i++) {for (var j = 0;j < Arr.length; J + + ) {if (I!=j&&math.abs (i-j) = = MaTh.abs (Arr[i]-arr[j]) {return true;}}} return false;}


8 Queen's question-backtracking (recursive)

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.