Basic design program and algorithms (ii) "" Second Week recursive "N Queens

https://www.cnblogs.com/franknihao/p/9416145.html

 

Question: chess board is 8x8 squares, each square Gerry put a piece. Queen Such pieces can attack the same row or the same column or oblique (lower left upper right lower right upper left four directions) on the pieces.

On a board if you want to put eight queens so that they can not attack each other (ie not any different columns of different counterparts slash between any two), obtained one kind of (further, all) layout.

/ * 
The Recurse 
N Queens problem 
* / 
#include <the iostream> 
#include <the cmath>
 the using  namespace STD; 

void NQueen ( int K);
 int N;
 // used to store positions quite good queens. The upper left corner is (0,0) 
int queenPos [ 100 ]; 

int main () 
{ 
    CIN >> N; 
    NQueen ( 0 ); // start swing from 0 Queen line 

    return  0 ; 
} 
// at 0 ~ k 1 Queen case where the row have been set, the pendulum k-th row and the queen 
void NQueen ( int k) 
{
    
    int I;
     IF (K == N) // N queens have been set 
    {
         for (I = 0 ; I <N; I ++ ) 
        { 
            COUT << queenPos [I] + . 1 << "  " ; 
        } 
        COUT << endl ;
         return ; 
        
    } 
    // by the k-th attempt queen positions
     // 0 ~ N columns traversal, the first K rows of columns should be placed in the queen 
    for (I = 0 ; I <N; I ++ ) 
    { 
        int J;
         for ( = J 0 ; J <K; J ++) 
        { 
            
            // positions have been set and the k queen comparison to see if the conflict
             @ 1 can not be in the same column
             @ 2 can not be on a diagonal line, i.e., line spacing! Row spacing = 
            IF (queenPos [J] == I || ABS (K - J) == ABS (I - queenPos [J])) 
            { 
                BREAK ; // conflict, the next position is again 
            } 
        } 
        IF (J = k =) // currently selected location does not conflict i 
        { 
            queenPos [k] = i; // the k queens placed in position i 
            NQueen (k + . 1 ); 
        } 
    } 
}

 

Guess you like

Origin www.cnblogs.com/focus-z/p/11409968.html