求助求助

P1219 [USACO1.5] 八皇后 Checker Challenge

Do_www @ 2023-09-21 23:28:19

对每行进行搜索时,输出判断u==n为什么过不去,但u > n 就能过。没想明白

#include<bits/stdc++.h>

using namespace std;

const int N = 100;
bool col[N],dg[N*2],udg[N*2];
int ans[N];
int n;
int total;
void dfs(int u)
{
    if(u == n)
    {
        if(total <= 2)
        {
            for(int k = 1 ; k <= n; k ++)
            {
                cout << ans[k]<<" ";
            }
            cout <<endl;
        }
        total ++;
    }
    for(int i = 1; i <= n ; i ++)
    {
        if(!col[i] && !dg[u + i] && !udg[u - i + n])
        {
            ans[u] = i;
            col[i] = dg[u + i] = udg[u - i + n] = true;
            dfs(u + 1);
            col[i] = dg[u + i] = udg[u - i + n] = false;
        }
    }
}
int main()
{
    cin >> n;
    dfs(1);
    cout << total <<endl;
    return 0;
}

|