c ++ n queens problem

Title Description

People play chess very clear: the queen can not eat another piece to the number of steps in the horizontal, vertical, diagonal. How eight queens on the chessboard (8 * 8 squares), so that they can not be eaten by anyone! This is the famous eight queens problem.

Entry

An integer n (1 <= n <= 10)

Export

Each output line corresponds to one approach, the column number of each program sequentially output in each row where the queen, adjacent two numbers separated by spaces, according to the dictionary order output. If the corresponding program does not exist, the output of -1.

Sample input

4

Sample Output

2 4 1 3
3 1 4 2

Source Code

#include <bits/stdc++.h>
using namespace std;
bool used[11];
int g[11][11];
int n;
bool flag=0;
bool check(int x,int y)
{
    int xx = x,yy = y;
    while(x >= 1&&y >= 1)
    {
        if(g[x][y] == 1) return 0;
        x--,y--;
    }
    x = xx,y = yy;
    while(x >= 1&&y <= n)
    {
        if(g[x][y] == 1) return 0;
        x--,y++;
    }
    return 1;
}
void dfs(int u)
{
    if(u == n + 1)
    {
        for(int i = 1;i <= n;i ++)
        {
            for(int j = 1;j <= n;j ++)
            if(g[i][j] == 1)
            {
                printf("%d ",j);
                break;
            }
        }
        printf("\n");
        flag = 1;
    }
    for (int i = 1;i <= n;i ++)
    if(used[i] == 0&&check(u,i) == 1)
    {
        g[u][i] = 1;
        used[i] = 1;
        dfs(u + 1);
        used[i] = 0;
        g[u][i] = 0;
    }
}
int main()
{
    cin >> n;
    memset(used,0,sizeof(used));
    memset(g,0,sizeof(g));
    dfs(1);
    if(flag == 0) cout << -1 << endl;
    return 0;
}

Guess you like

Origin www.cnblogs.com/LJA001162/p/11334919.html