C + + Backtracking algorithm Demo: Take the 4 queen problem as an example

Source: Internet
Author: User

The backtracking algorithm actually constructs an inference tree and outputs the historical steps in reverse from the leaf nodes of the tree;

Among them, the construction process of the tree is more complicated, and a simplified method is to connect and construct the relationship of each node using the linked list;

In the case of the 4 queen problem, the C + + vector container is used to avoid the use of pointers (which, of course, replace the position of the pointer with an integer), which solves the problem. The whole algorithm is clear and easy to understand.

See Code; Unlike in the book, this code actually outputs the different ways of all 4 queens.


Title:4 Queen problem backtracking algorithm for solving//demo:1) backtracking algorithm to achieve the 4 queen problem; 2) Difficulties: the expression of the tree structure, 3) The expression of tree structure with linear container, and the realization of tree scanning-reducing the difficulty of tree implementation//author:liping chen// Email: [email protected]//published date:20125-4-11#include <iostream> #include <string.h> #include <vector> #include <stdlib.h>using namespace std;//definition 4 Queen's Chess data structure and method typedef struct QUEEN4 {int Vals[16];int Nqueens;int parent;//default constructor Queen4 () {for (int i = 0; i <; i++) vals[i] = 0; parent = 0;nqueens = 0;} Constructor 1queen4 (int nvals[16]) {for (int i = 0; i <; i++) vals[i] = nvals[i]; parent = 0;nqueens = 0;} Locate the position in the current layout that is not 0 int getPosition () {for (int i = 0; i <; i++) if (vals[i] = = 0) {return i;} return-1;} Mark Horizontal, vertical, and diagonal position masks void Setqueen (int pos) {int row, col;vals[pos] = 1;nqueens++;row = Pos/4;col = pos% 4;for (int) When setting the Queen position c = 1; C <= 3;  C + +) {//lower right if (row + C < 4 && col + C < 4) if (vals[(row + C) * 4 + (col + c)] = = 0) vals[(row + C) * 4 + (col + c)] = 2;//left upper if (row-c >= 0 && col-c >= 0) if (vals[(Row-C) * 4 + (col-c)] = = 0) vals[(row-c) * 4 + (col-c)] = 2;//left down if (row + C < 4 && col-c >= 0) if (vals[( Row + C) * 4 + (col-c)] = = 0) vals[(row + C) * 4 + (col-c)] = 2;//Right upper if (row-c >= 0 && col + C >= 0) if  (vals[(ROW-C) * 4 + (col + c)] = = 0) vals[(row-c) * 4 + (col + c)] = 2;//Right Horizontal if (col + C < 4) if (Vals[row * 4 + (col  + c)] = = 0) Vals[row * 4 + (col + c)] = 2;//Left horizontal if (col-c >= 0) if (Vals[row * 4 + (col-c)] = = 0) Vals[row * 4 + (col  -c)] = 2;//under if (Row + C < 4) if (vals[(row + C) * 4 + col] = = 0) vals[(row + C) * 4 + col] = 2;//on if (row-c >= 0) if (vals[(row-c) * 4 + col] = = 0) vals[(row-c) * 4 + col] = 2;}}  Output current game void output (int level) {int cnt = 0;char chars[100];for (int k = 0, K < level; k++) chars[k] = "; Chars[level] = cout << chars << "queen4=" << Endl << chars;for (int i = 0; i <) i++) {cout << V Als[i] << ""; Cnt++;if (cnt% 4 = = 0) cout << endl << chars;}}//Recursive call output historical chess game void Outputhist (vector<queen4>& tr) {if (parent) tr[parent].outputhist (tr); output (0);} Generated by the current layout of the chess next layout void reproduce (vector<queen4>& tr, int pos) {int Nvals[16];bool inserted;//think: Why use Nvalsfor (int i = 0; i < i++) Nvals[i] = vals[i];for (int i = 0; i < i++) {if (nvals[i] = = 0) {Nvals[i] = 1;//new result join container Qu EEN4 Q (tr[pos].vals); Q.setqueen (i); q.parent = Pos;tr.push_back (q);}}} queen4;//program main function int main () {QUEEN4 q0;//call default constructor vector<queen4> tr;//vector container-function equivalent to queue, you can add a new checkerboard layout int levels[1024]      = {0};//records the number of children per layer-for layered tr.push_back (q0);//Add the initial checkerboard to the container int oldn = 0, newn = 1, level = 0; Storage variables//Jeangen node generate new child and add new child to container//If no new child is created, then the answer is found//then the bottom is the answer (need to record the number of children produced per layer) while (newn! = oldn) {//Let the last child produce new child for (int i = OLDN; i < newn; i++) tr[i].reproduce (tr, i);//update the number of old children and new children oldn = newn;levels[++level] = newn;newn = Tr.size (); }OLDN = 1;//Output 4 Queen problem how many solutions for (int i = levels[level-1]; i < levels[level]; i++) {cout << "4 Queen Placement method:" << oldn+ + << Endl;tr[I].outputhist (TR);} return 0;}


C + + Backtracking algorithm Demo: Take the 4 queen problem as an example

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.