代码检查了几遍都没发现问题,提交就0分求助大佬

P1219 [USACO1.5] 八皇后 Checker Challenge

wp_43_xyzy @ 2024-07-09 17:53:03

蒟蒻求助大佬,代码如下:

#include<bits/stdc++.h>
using namespace std;
int a[115], c[5][128] = {0}, sum=0, n;
void wp(int l) {
    if (l > n) {
        sum++;
        if (sum > 3) {
            return;
        } else {
            for (int i = 1; i <= n; i++) {
                cout << a[i]<<" ";
            }
            cout<<endl;
            return;
        }
    }
    for (int i = 1; i <= n; i++) {
        if ((!c[0][i]) && (!c[i][l + i] )&& (!c[2][l - i + n])) {
            a[l] = i;
            c[0][i] = 1;
            c[1][l + i] = 1;
            c[2][l - i + n] = 1;
            wp(l + 1);
            c[0][i] = 0;
            c[1][l + i] = 0;
            c[2][l - i + n] = 0;
        }
    }
}
int main() {
    cin >> n;
    wp(1);
    cout << sum;
    return 0;
}


by LoveYuigahamaYui @ 2024-07-09 17:56:23

思路都在代码里~

#include <iostream>
#include <cmath>
using namespace std;

int n;
int ans = 0;
int a[20];  // 行 - 存答案 - "第几行第几列放了一个皇后"
bool b[20], c[20], d[20]; // 同列;同对角线 - 正对角线[x + y] - 负对角线[abs(x - y)](以防数组越界)

void print() 
{
    for (int i = 1; i <= n; ++i) cout << a[i] << " ";
    cout << endl;
}

void dfs(int dep) 
{ // 按行枚举
    if (dep > n)
    { // 一次搜索结束
        dep = 1; // 重新开始 - 初始化
        ans++; // 方案数++
        if (ans <= 3) print(); // 输出前 3 个答案
    }
    for (int i = 1; i <= n; i++) 
    {
        if (!b[i] && !c[dep + i] && !d[dep - i + n]) 
        { // 能放
            a[dep] = i;
            b[i] = true;
            c[dep + i] = true;
            d[dep - i + n] = true;
            dfs(dep + 1);
            b[i] = false; // 恢复状态
            c[dep + i] = false;
            d[dep - i + n] = false;
        }
    }
}

int main() 
{
    cin >> n;
    dfs(1);
    cout << ans << endl;
    return 0;
}

by Fish_Love_Water @ 2024-07-09 18:00:00

@wp_43_xyzy 18行1写成i了,建议下次不要用这种数组

if((!c[0][i]) && (!c[1][l + i] )&& (!c[2][l - i + n])) 

求关


by Fish_Love_Water @ 2024-07-09 18:00:55

@LoveYuigahamaYui 人家思路没错吧


by wp_43_xyzy @ 2024-07-09 18:01:31

@LoveYuigahamaYui 找到错误在哪里了``` if ((!c[0][i]) && (!c[i][l + i] )&& (!c[2][l - i + n]))

中第二个判断条件错了,应该改成:

(!c[1][l + i] )


1和i

by wp_43_xyzy @ 2024-07-10 09:02:13

@Fish_Love_Water 感谢大佬,已关


|