Hangzhou Electric - 2553 N Queens Problem

 

The meaning of problems and ideas

Meaning of the questions: for example, in the eight queens problem, the 8 * 8 squares, placing eight queens. Queen's not a requirement not in the same row, not in the same column, and not on the same connection.

Ideas: Taking into account each row of each column can have only one queen, which can be seen as a full array of issues n, just a little improvement on the n queens problem can be achieved. The approach is simple , each time getting a number of permutations to determine the legality of each two queens, but this approach is not optimal. Better yet , each time you want to place the first line of the Queen index, determine whether the location is already illegal, if the illegal operations do not need to do a lot of follow-up, similar to the back , but this has a little different. If legitimate, then added, recursively execute the next line of the Queen of the pendulum law issues.

Stepped pit: Recursive eight queens problem of backtracking to achieve in-depth understanding of some recursive, otherwise he might convince himself, thinking easily infinite loop. Secondly there is little need to open up some space has been stored n-queens problem well, such as 8 queens problem is already solved, it will be stored in Memory [n] the memory unit to the next time can be output directly. If not toss, it will TLE up.

 

Code

#include <iostream>
#include <cstdio>
#include <math.h>

using namespace std;

const int MAXSIZE = 100;
int n,P[MAXSIZE],cnt=0;
int memory[MAXSIZE] = {0};
bool hashTable[MAXSIZE] = {false};

void Nqueue(int index){
    if(index == n+1){
        cnt++;
        memory[n]++;
        return;
    }
    for(int x=1;x<=n;x++){ //第x列 
        if(hashTable[x] == false){ //第x列还没有皇后
            bool f = true; //f为true表示当前皇后不会和之前的皇后冲突
            for(int pre=1;pre<index;pre++){
                if(abs(index-pre) == abs(x-P[pre])){
                    f = false;
                    break;
                }
            }
            if(f){
                P[index] = x; //将当前index行的皇后放在x列上 
                hashTable[x] = true;
                Nqueue(index + 1); //处理下一行 
                hashTable[x] = false; //处理一个摆法完毕,递归回掉 
            }
        } 
    }
    
}

int main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(0);
    while(scanf("%d",&n)!=EOF && n!=0){
        cnt = 0;
        if(memory[n]==0){
            Nqueue(1); //从第一行开始 
            cout << cnt << endl;
        }else
            cout << memory[n] << endl;            
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/kyrie211/p/11273868.html