回溯法与八皇后问题

https://www.cnblogs.com/bigmoyan/p/4521683.html

#include<iostream>
#include<math.h>
using namespace std;

int n=8;
int total=0;
int *c=new int(n);

bool is_ok(int row){
    for(int j=0;j!=row;j++){
        if(c[row]==c[j] || row-c[row]==j-c[j] || row+c[row]==j+c[j])
            return false;
    }
    return true;
}

void queen(int row){
    if(row==n)
        total++;
    else
        for(int col=0;col!=n;col++){
            c[row]=col;
            if(is_ok(row))
                queen(row+1);
        }       
}

int main(){
    queen(0);
    cout<<total;
    return 1;
}

猜你喜欢

转载自www.cnblogs.com/captain-dl/p/10093478.html