NiffrG 2022-08-10 21:25 采纳率: 0%
浏览 19
已结题

DFS & BFS搜索模板题代码出现问题

原题:【HDU1312:Red and Black】 http://59.61.214.20:3000/contest/418/problem/3
两段程序都有问题,不知道为啥。。

#include <bits/stdc++.h>
#define elif else if
using namespace std;
inline void init();
//var:(main)
int h, w, x, y;
bool a[52][52];
int dx[5] = {0, -1, 1, 0, 0};
int dy[5] = {0, 0, 0, -1, 1};
char ch;
queue<int> qx, qy;
int ans;

inline int BFS() {
    qx.push(x);
    qy.push(y);
    while(!qx.empty() and !qy.empty()) {
        for(int i = 1; i <= 4; i++) {
            x = qx.front() + dx[i];
            y = qy.front() + dy[i];
            if(a[x][y]) {
                ans++;
                qx.push(x);
                qy.push(y);
                a[x][y] = false;
            }
        }
        qx.pop();
        qy.pop();
    }
    return ans;
}

int main() {
    init();
    cin >> h >> w;
    for(int i = 1; i <= w; i++) {
        for(int j = 1; j <= h; j++) {
            ch = getchar();
            if(ch == '.') a[i][j] = true;
            elif(ch == '@') {
                x = i;
                y = j;
                a[i][j] = false;
            }
        }
        getchar();
    }
    cout << BFS() + 1 << '\n';
    return 0;
}

inline void init() {
    freopen("tile.in", "r", stdin);
    freopen("tile.out", "w", stdout);
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
}



```c++

#include <bits/stdc++.h>
#define elif else if
using namespace std;
inline void init();
//var:(main)
int h, w, x, y;
bool a[52][52];
int dx[5] = {0, -1, 1, 0, 0};
int dy[5] = {0, 0, 0, -1, 1};
char ch;
int ans;

inline void DFS(int x, int y) {
    a[x][y] = false;
    ans++;
    for(int i = 1; i <= 4; i++)
        if(a[x + dx[i]][y + dy[i]])
            DFS(x + dx[i], y + dy[i]);
}

int main() {
    init();
    cin >> h >> w;
    for(int i = 1; i <= w; i++) {
        for(int j = 1; j <= h; j++) {
            ch = getchar();
            if(ch == '.') a[i][j] = true;
            elif(ch == '@') {
                x = i;
                y = j;
                a[i][j] = true;
            }
        }
        getchar();
    }
    DFS(x, y);
    cout << ans << '\n';
    return 0;
}

inline void init() {
    freopen("tile.in", "r", stdin);
    freopen("tile.out", "w", stdout);
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
}
  • 写回答

2条回答 默认 最新

  • 烟雨龙升 2022-08-10 22:14
    关注

    你的bfs和dfs都有一点,就是没有判断溢出的情况。如果你的x或y小于0了怎么办,你的x或y大于给定的边界值了怎么办。
    注意这些点

    这些不考虑不就意味着走着停不下来了。

    评论 编辑记录

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 8月23日
  • 创建了问题 8月10日