求调(玄关)

P1219 [USACO1.5] 八皇后 Checker Challenge

wisdom2010 @ 2024-07-18 16:22:14

#include<bits/stdc++.h>
using namespace std;
int n;
const int maxn = 15;
int dis[maxn][maxn] = {0};
int ans = 0;
struct Q
{
    int x;
    int y;
}q[maxn];
void dfs(int step)
{
    if(step == n)
    {
        ans++;
        if(ans <= 3)
        {
            for(int i = 0; i < n; i++)
                printf("%d ", q[i].x + 1);
            printf("\n");
        }
        return ;
    }
    for(int i = 0; i < n; i++)
    {
        if(dis[step][i] == -1)
            continue;
        q[step].x = i;
        q[step].y = step;
        for(int j = 0; j < n; j++)//标记行和列
        {
            dis[step][j] = -1;
            dis[j][q[step].x] = -1;
        }
        for(int j = 1; j <= max(q[step].x - 1, n - q[step].x); j++)//标记对角线
        {
            if(q[step].x - j >= 0 && q[step].y - j >= 0)
                dis[q[step].x - j][q[step].y - 1] = -1;
            if(q[step].x + j <= n && q[step].y + j <= n)
                dis[q[step].x + j][q[step]. y + j] = -1;
        }
        dfs(step + 1);
        dis[step][q[step].x] = 0;//消除标记
        for(int j = 0; j < n; j++)
        {
            dis[step][j] = 0;
            dis[j][q[step].x] = 0;
        }
        for(int j = 1; j <= max(q[step].x - 1, n - q[step].x); j++)
        {
            if(q[step].x - j >= 0 && q[step].y - j >= 0)
                dis[q[step].x - j][q[step].y - 1] = 0;
            if(q[step].x + j <= n && q[step].y + j <= n)
                dis[q[step].x + j][q[step]. y + j] = 0;
        }
    }
}
int main()
{
    scanf("%d", &n);
    dfs(0);
    printf("%d", ans);
    return 0;
}

by An_Idiot @ 2024-07-18 16:45:22

@wisdom2010 感觉你算法的使用不对。

#include<bits/stdc++.h>
using namespace std;
long long n,ans,a[105],b[105],c[105],d[105];
void dfs(long long x)
{
    if(x==n+1)
    {
        if(ans<3){for(int i=1;i<=n;i++) cout<<a[i]<<" ";cout<<endl;}
        ans++;
    }
    for(int i=1;i<=n;i++) 
    if((!b[i]) && (!c[x+i]) && (!d[x-i+n])) 
    a[x]=i,b[i]=1,c[x+i]=1,d[x-i+n]=1,dfs(x+1),a[x]=0,b[i]=0,c[x+i]=0,d[x-i+n]=0;
}
int main() {
    cin>>n,dfs(1),cout<<ans;
    return 0;
}

这是我打的比较简洁的代码,你可以看一下


by wisdom2010 @ 2024-07-18 18:11:24

@An_Idiot 谢谢,我再改一改,有不懂的再请教您!


by An_Idiot @ 2024-07-18 18:12:22

@wisdom2010 没事


by wisdom2010 @ 2024-07-18 19:14:09

@An_Idiot 抱歉还得麻烦您,我看明白了你的思想,但我还是不知道我的代码哪错了...qwq


by An_Idiot @ 2024-07-18 19:17:25

@wisdom2010 那我帮你看看吧


by An_Idiot @ 2024-07-18 19:17:50

@wisdom2010 对了,不要叫 “您”,我是蒟蒻。。


by wisdom2010 @ 2024-07-18 19:20:00

@An_Idiot 谢谢


by wisdom2010 @ 2024-07-18 19:21:55

@An_Idiot 不用在意这些细节,我还有好多东西向你学习呢,交个朋友吧~


by An_Idiot @ 2024-07-18 19:22:17

@wisdom2010 行啊


by An_Idiot @ 2024-07-18 19:22:55

@wisdom2010 我关注你惹,如果你有什么问题可以来问我(前提是我会.....)!


| 下一页