N Queens (recursive) - Learning Algorithm

problem

Enter a positive integer, then the program outputs all N queens problem Pendulum output in each row represents a pendulum method, the i-th row in the figures
, if n is, on behalf of the i-th row in the n-queens should column. Queen of the row and column numbers are counted from the beginning of 1

Problem-solving ideas

From the array of row 0 of 0 create start placing the Queen, followed by placing the first line of the Queen, when they are placed behind each time to start playback from 0 to determine whether a conflict, if not conflict, then placed in 2 rows ... n the line. If the conflict is changed on one line, then the Queen's position, placed to continue to the next line.

Code:

#include<iostream>
#include<cmath>
using namespace std;
int N;
int queenPos[100];
void NQueen(int k);
int main() {
    cin >> N;
    NQueen(0);
    return 0;
}
void NQueen(int k) {
    int i;
    if (k == N) {
        //N个皇后已经摆好
        //则只需要输出皇后的位置
        for (i = 0; i < N; i++)
            cout << queenPos[i] + 1 << " ,";
        cout << endl;
        return;
    }
    //如果没有摆好
    for(i=0;i<N;i++)//逐个尝试第k个皇后的位置
    {
        int j;
        for (j = 0; j < k; j++) {
            //和已经摆好的皇后的位置比较,看是否位置冲突
            if (queenPos[j] == i || abs(queenPos[j] - i) == abs(k - j)) 
            { //如果成立就是位置冲突,则跳出这一行到上一行
                break;
            }
            if (j == k)
            {//当前位置不冲突
                queenPos[k] = i;//将第k个皇后摆放在位置i
                NQueen(k + 1);
            }
        }
    }
}
Published 79 original articles · won praise 133 · views 40000 +

Guess you like

Origin blog.csdn.net/weixin_45822638/article/details/105027862