Eight queens problem algorithm notes

Eight Queens has been a common one interview subject, then I come to this question is described

Here Insert Picture Description
Violence algorithm can think of is the direct use of violence to determine the cycle twice. Determine the Queen's problem is that in the same row 2. 1. same column, 2. Not in the same diagonal, then that is iterative, recursive judgment.

#include <stdio.h>
#include <stdlib.h>
//我首先分析一下问题,就是八皇后,在一个8*8的矩阵中放8个皇后,也就是一行一个,一列一个
//每行必定有一个,所以从第0行开始,for循环0到n-1个位置都可以放一个,判断是否可以,如果可以的话
//就递归下一行,直到大于8,就总次数大于一。
//以下是伪代码
//首先是一个数组用来存行列,数组下标就是对应的行,数组里的值就是对应的列,如 a[1]=1 就表示在1行1列
//开始写方法来判断,第n个皇后是否合格
int  sum=0;//这是总次数
int i,j;

bool  way(int a[],int n){
    for(int i=0;i<n;i++){
        if(a[i]==a[n]&&abs(i-n)==abs(a[i]-a[n]){
           return false;
        }
    }
    return true;
}
//开始写递归方法
void digui(int n){
    //这个开头是在我结束之后想明白补充上去的,因为每一个递归相当于一层,一层里的加法和累积加法无关
    if(n>8){
        sum++;
    }
    for(i=0;i<8;i++){
        a[n]=i;//输入某一行的某一列
        //开始判断
        if(way(a,n)){//意思就是如果可以的话,那就判断下一行
                digui(n+1);
        }
    }
}

Published 72 original articles · won praise 5 · Views 2830

Guess you like

Origin blog.csdn.net/qq_41115379/article/details/104838905