<Base> <back> Eight Queens problem

1.Intro

This is a question raised by the international chess player marks in 1848. Placed on the 8x8 grid of eight chess queens, it can not attack each other, that is, any two queens can not be in the same column on the same row or the same slash and asked how many pendulum method. Our computer programming to solve this problem.

2.Solution

First try violent direct method, nested 8 cycles, in state space 8 ^ 8, so huge, abandoned.

Slightly thinking, you can use backtracking to solve the Austrian.

Backtrack backtrack say

 

= Result [] 
DEF Fuc (path selection list):
  IF termination condition is satisfied:
    result.add (path)
  
  for selection in the selection list:
    to choose
    Fuc (path selection list)
    deselection

 

Back with recursion, for circulation in a recursive, recursive make choices before, after the recursive call deselection.

Try to use backtracking to solve the eight queens problem, write code:

#include<bits/stdc++.h>
using namespace std;
short arr[8];
int result = 0;
bool isValid(int x,int y){
    if(x==0){
        return 1;
    }

    for(int i=0;i<x;i++){
        if(arr[i]==y | abs(arr[i]-y)==abs(i-x)){
            return 0;
        }
    }
    return 1;
}
    
void fuc(int col){
    if(col==8){
        result++;
        return;
    }
    
    for(int i=0;i<8;i++){
        if(isValid(col,i)){
            arr[col]=i;
            fuc(col+1);
        }
    }        
}
int main(){
    fuc(0);
    cout<<result<<endl;
    return 0;
}

In the above code, we uphold such ideas to solve the problem: look at the column 0, look at the first column, look at the first two columns until the seventh. Put a queen on each column.

arr [8] represents the array of the board placed in the case, for example, arr [3] = 6 indicates that there is a queen (3,6) positions;

result is a count variable, when found to result after a possible embodiment ++;

isValid (int x, int y) function used to determine the time to see if the Queen in column x (x, Y) location of the front will conflict columns x-1, can put a return, not put returns 0 ;

fuc (int col) function is the main body, representing the first col columns see the situation of the time.

 Also can be seen from here, in fact backtracking algorithm can be considered a brute force, a high degree of complexity, because it uses a recursive speed certainly can not be considered fast, while it is not like DP overlapping sub-problems can be optimized.

 emmm ------ temporarily just want to write back this kind of solution, the future will likely expand to other bar.

3.Extension

Well, to find a viable solution Eight Queens, followed by promotion to the n queens problem.

8 as long as the above code to replace all the n Jiuhaola

Guess you like

Origin www.cnblogs.com/dynmi/p/12128747.html