N皇后问题

第一种写法,按行枚举

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
using namespace std;


const int N = 20;

char g[N][N];
bool col[N], dg[N], udg[N];
int n;




void dfs(int u)
{
    if(u == n)
    {
        for(int i = 0; i < n; i ++ )  puts(g[i]);
        puts("");
        return;
    }

    for(int i = 0; i < n; i ++ )
    {
        if(!col[i] && !dg[u + i] && !udg[n - u + i])
        {
            g[u][i] = 'Q';
            col[i] = dg[u + i] = udg[n - u + i] = true;
            dfs(u + 1);
            col[i] = dg[u + i] = udg[n - u + i] = false;
            g[u][i]= '.';
        }
    }
}

int main()
{
    cin >> n;
    for(int i = 0; i < n; i ++ )
        for(int j = 0; j < n; j ++ )
            g[i][j] = '.';

    dfs(0);
    return 0;
}

第二种写法,一格一格枚举

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
using namespace std;

const int N = 20;
bool row[N], col[N], dg[N], udg[N];
char g[N][N];
int n;


void dfs(int x, int y, int s)
{
    if(y == n)  y = 0, x ++;

    if(x == n)
    {
        if(s == n)
        {
            for(int i = 0; i < n; i ++) puts(g[i]);
            puts("");
        }
        return;
    }

    dfs(x, y + 1, s);

    if(!row[x] && !col[y] && !dg[x + y] && !udg[x - y + n])
    {
        g[x][y] = 'Q';
        row[x] = col[y] = dg[x + y] = udg[x - y + n] = true;
        dfs(x, y + 1, s + 1);
        row[x] = col[y] = dg[x + y] = udg[x - y + n] = false;
        g[x][y] = '.';
    }
}

int main()
{
    cin >> n;

    for(int i = 0; i < n; i ++ )
        for(int j = 0; j < n; j ++ )
            g[i][j] = '.';

    dfs(0, 0, 0);
    return 0;
}
yitao 支付宝支付宝
yitao 微信微信
0%