Loading

P1219 [USACO1.5]八皇后 Checker Challenge

题目链接

https://www.luogu.com.cn/problem/P1219

题目思路

dfs搜索,枚举每一行,查找合法的位置
关键:正对角线用一维表示为 \(u + i\),反对角线为了不超范围表示为 \(n - u + i\)

题目代码

#include <iostream>
#include <algorithm>

using namespace std;
const int N = 110;
int g[N][N];
bool row[N], dg[N], udg[N];
int n, cnt;;

int dfs(int u)
{
    if(u == n)
    {
        if(cnt < 3)
        {
            for(int i = 0; i < n; i ++ )
            {
                for(int j = 0; j < n; j ++ )
                    if(g[i][j] == 1) cout << j + 1 << ' ';
            }
            puts("");
        }
        cnt ++ ;
        return 0;
    }
    
    for(int i = 0; i < n; i ++ )
    {
        if(!row[i] && !dg[u + i] && !udg[n - u + i ] && g[u][i] == 0)
        {
            g[u][i] = 1;
            row[i] = dg[u + i] = udg[n - u + i] = true;
            dfs(u + 1);
            g[u][i] = 0;
            row[i] = dg[u + i] = udg[n - u + i] = false;
        }
    }
}

int main()
{
    cin >> n;
    dfs(0);
    cout << cnt << endl;
    return 0;
}
posted @ 2022-03-24 21:01  vacilie  阅读(51)  评论(0)    收藏  举报