AcWing 1432 board challenge

Title description:

Given a chessboard of N×NN×N, please place NN pieces on it, and the requirements are as follows:

  • There is exactly one pawn in each row and column
  • There can be at most one piece on each diagonal
    1   2   3   4   5   6
  -------------------------
1 |   | O |   |   |   |   |
  -------------------------
2 |   |   |   | O |   |   |
  -------------------------
3 |   |   |   |   |   | O |
  -------------------------
4 | O |   |   |   |   |   |
  -------------------------
5 |   |   | O |   |   |   |
  -------------------------
6 |   |   |   |   | O |   |
  -------------------------

The above figure shows a solution when N=6N=6. The solution can  2 4 6 1 3 5 be described by a sequence. The sequence shows the column of the chess pieces placed in each row from the first row to the sixth row in order. s position.

Please write a program, given an N×NN×N chessboard and NN chess pieces, please find out all the chess placement schemes that meet the above conditions.

Input format

A total of one line, an integer NN.

Output format

There are four lines in total, each of the first three lines outputs a sequence of integers to describe a feasible placement plan. The iith number in the sequence indicates the position of the column where the pawns in the iith row should be placed.

The scheme described by these three lines should be the scheme with the integer sequence lexicographically ranked first, second, and third.

The fourth line outputs an integer that represents the total number of possible placement options.

data range

6≤N≤136≤N≤13

Input sample:

6

Sample output:

2 4 6 1 3 5
3 6 2 5 1 4
4 1 5 2 6 3
4

 

#include <iostream>
#include <cstdio>

using namespace std;
const int MAX = 20;

int a[MAX][MAX];
bool col[MAX], L[2 * MAX], R[2 * MAX];
int ans[MAX];
int n, cou;

void dfs(int u)
{
    if(u > n)
    {

        if(cou < 3)
        {
            for(int i = 1; i <= n; i++)
                printf("%d ", ans[i]);
            printf("\n");
        }
        cou++;
        return;
    }

    for(int i = 1; i <= n; i++)
    {
        if(!col[i] && !L[i + u] && !R[u - i + n])
        {
            col[i] = L[i + u] = R[u - i + n] = true;
            ans[u] = i;
            dfs(u + 1);
            col[i] = L[i + u] = R[u - i + n] = false;
        }
    }
}

int main()
{
    scanf("%d", &n);
    dfs(1);
    printf("%d\n", cou);
    return 0;
}

 

Guess you like

Origin blog.csdn.net/weixin_44620183/article/details/113461064