N Queens (recursive backtracking thought)

Eight queens problem is an old and well-known problem is backtracking algorithms typical cases. The problem is an international chess player Max Bethel presented in 1848: placed on the international chess 8 × 8 grid of eight Queens, it can not attack each other, that any two queens can not be in the same line, on the same row or the same slash and asked how many pendulum method.

Thus come to develop N Queens

The number of first seeking the solution: // backtracking algorithm is the brute-force method

1. Each row put a queen

2. Lower the line when the judge: Will there be the same column, will appear the same slash. The slope determination can be attributed to slash Analyzing.

// recursive backtracking code is as follows: 
#include <the iostream> the using namespace STD; #include <math.h> #define N 16 int n-; // number Queen int SUM = 0 ; // number of feasible solutions int X [N ]; // tag Queen columns placed BOOL the Agree ( int K) { int I; for (I = . 1 ; I <K; I ++ ) IF (ABS (K - I) == ABS (X [K] - X [I]) || X [K] == X [I]) return to false ; return to true ; } Int Queen ( int T) { IF (T> n && n> 0 ) // when placed Queen exceeds n, the number of feasible solutions plus 1, where n must be greater than 0 SUM ++ ; the else for ( int I = 1 ; I <= n-; I ++ ) { X [T] = I; // tag IF (the Agree (T)) Queen (T + . 1 ); } return SUM; } int main () { int T; CIN >> n-; T = Queen (1); cout << t; return 0; }

Since then supplemented iteration ---------------- ------------------ backtracking algorithm

 

Guess you like

Origin www.cnblogs.com/yoriko/p/12234946.html