n Queen question (n Queen ' s problem)

Source: Internet
Author: User

The N Queen problem is an old and famous problem, a typical case of the backtracking algorithm (back track). The problem is described as follows:

n x N on the chessboard Place n Queens. Requires only one queen in the same row, in the same column, and on the diagonal (including the positive and negative diagonal), or it will fail if clash occurs. Ask the solution?

The solution is as follows:

(1) Scan by column, starting from the leftmost column, with a total of n queens.

(2) Returns True if all queens are safely placed.

(3) For a given column, try all the rows, the row is a variable, note that at this time all the columns on the left of this column are placed Queen, at this time we just need to scan all the rows of the current column, looking for the feasible row, so-called feasible is not with the left Queen to produce clash, the condition is three directions, Different columns (of course will meet), not peers, different on diagonal diagonal, different diagonally diagonal.

(4) Once you have placed the queen of the current column, go to the next column and place it. However, once there is no feasible solution, it is necessary to backtrack (backtrack) to the previous column, re-place the previous column of the Queen, continue repeating the above steps until successful, otherwise the output fails.

Refer to the following procedure (4 * 4) for reference to Geeks for geeks:

#include <iostream> #include <cstdio>using namespace std;const int N = 4;//a utility functionvoid Printsolutio n (int board[n][n]) {for (int i = 0, i < n; ++i) {for (int j = 0; j < N; ++j) {cout << bo        ARD[I][J];    } cout << Endl;  }}//a utility function to Chreck if a queen can//being placed on Board[row][col], note this function//was called when ' col ' Queens already placed in columns//from 0 to col-1, so we need to check only left side//for attacking Queensbool Issaf E (int board[n][n], int row, int col) {//check row on left side for (int i = 0; i < col; ++i) {if (board[r        Ow][i]) {return false;        }}//Check upper diagonal on left side for (int i = row, j = col; I >= 0 && J >= 0; I,--j) {        if (Board[i][j]) {return false;  }}//Check lower diagonal on the left side for (int i = row, j = col; i < N && J < col; ++i,--j) {      if (Board[i][j]) {return false; }} return true;  A recursive utility function to solve N queen//problembool solvenqutil (int board[n][n], int col) {//Base Case:if    All Queens is placed then return true if (Col >= N) {return true;        }//Consider this column and try placing this Queen in all rows//one by one for (int i = 0; i < N; i++) { Check if Queen can is placed on board//Board[i][col] if (issafe (board, I, col)) {//PL            Ace this queen on Board[i][col] board[i][col] = 1;            Recur to place the rest of the Queens if (Solvenqutil (board, col + 1) = = True) {return true; }//If placing Queen on Board[i][col] does//not leads to a solution, we should remove It board[i][col] = 0; Backtrack}}//If Queen cannot is placed in any row//In this column col, then return false RetuRN false;}    BOOL Solvenq () {int Board[n][n] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}};        if (solvenqutil (board, 0) = = False) {cout << "No solution" << Endl;    return false;        } else {printsolution (board);    return true;    }}//driver Programint Main () {Solvenq (); return 0;}
The results of the operation are as follows:


Referring to the wiki's http://en.wikibooks.org/wiki/Algorithm_Implementation/Miscellaneous/N-Queens, the following code produces all the possible solutions for all Nqueen:

#include <iostream>using namespace Std;const int N = 4;int Position[n]; Record the location of the solution's n Queen//check if a position is Safebool issafe (int queen_number, int row_position) {//Check if the row is safe/checked ea CH Queen before this onefor (int i = 0; i < Queen_number; i++) {//Current Queen the left column of the already secured queen//Get another queen ' s Row_pos Itionint other_row_pos = Position[i]; Previous Queen storage location at position[i]//now check if they ' re in the same row or diagonalsif (Other_row_pos = row_position | |//SA Me Rowother_row_pos = = row_position-(queen_number-i) | | Same Diagonalother_row_pos = = Row_position + (queen_number-i))//same diagonalreturn false;} return true;} Recursively generate a tuple like [0 0 0 0] and then [0 0 0 1] then etc ... void solve (int k) {if (k = = N)//We placed N-1 Queens (0 included), problem solved!{ Solution Found!cout << "solution:"; for (int i = 0; i < N; i++) cout << position[i] << ""; cout << Endl;} else{for (int i = 0; i < N; i++)//Generate all Combinations{//For the current K (the Queen placed in the K column), will try to play all rows//before putting a queen (the k-th queen) into a row, test it for Safenessif (Issafe (k, i))//can execute the following statement, place Queen K at position i {position[k] = i;//Place another queensolve (k + 1);}}} int main () {solve (0); return 0;}
The results of the operation are as follows:



n Queen question (n Queen ' s problem)

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.