Chapter 19: the eight queens problem

Knowledge points

There are many solutions to the eight queens problem. Here is the simplest backtracking solution.

Question link

ALDS1_13_A:8 Queens Problem

Question content

In the 8 * 8 chess board, there are k queens already placed. The queen will attack other pieces in her line, column and left and right diagonal sides, and ask how to put the 8 queens on the 8 * 8 board to ensure that they don't attack each other.

thinking

We try recursively. If the recursion is not successful, we will resume the original state and continue to try other recursions.

Code

#include<iostream>   
#include<cstdio>  
#include<algorithm>
#include<stack>
using namespace std;
const int maxx = 8;
// Column and column, slash
int row[maxx], col[maxx];
int dpos[maxx * 2 - 1], dneg[maxx * 2 - 1];

int x[maxx][maxx];

void init() {
    for (int i = 0; i < maxx; i++)
        row[i] = col[i] = 0;
    for (int i = 0; i < maxx * 2 - 1; i++)
        dpos[i] = dneg[i] = 0;
    for (int i = 0; i < maxx; i++)
        for (int j = 0; j < maxx; j++)
            x[i][j] = 0;
}
void print() {

    for (int i = 0; i < maxx; i++) {
        for (int j = 0; j < maxx; j++) {
            if (x[i][j] && row[i] != j)
                return;
        }
    }
    for (int i = 0; i < maxx; i++) {
        for (int j = 0; j < maxx; j++) {
            printf("%c", row[i] == j ? 'Q' : '.');
        }
        printf("\n");
    }
}
void recursive(int i) {
    if (i == maxx) {
        print();
        return;
    }

    for (int j = 0; j < maxx; j++) {
        // Not fit here
        if (col[j] || dpos[i + j] || dneg[i - j + maxx - 1])
            continue;

        // Try to put it down
        row[i] = j; col[j] = dpos[i + j] = dneg[i - j + maxx - 1] = 1;
        recursive(i + 1);
        // Resume the previous operation and continue other operations
        row[i] = col[j] = dpos[i + j] = dneg[i - j + maxx - 1] = 0;
    }
}
int main()
{
    int k;
    int r, c;
    scanf("%d", &k);
    for (int i = 0; i < k; i++){
        scanf("%d %d", &r, &c);
        x[r][c] = 1;
    }

    recursive(0);
    return 0;
}

Posted on Sun, 03 May 2020 07:58:07 -0400 by antonbrk