全部评论 2

  • #include<bits/stdc++.h>
    using namespace std;
    
    struct st {
        int x, y;
    };
    
    queue<st> a;
    char ca[55][55];
    int ia[55][55] = {0};  // 显式初始化访问标记数组
    int n, m;
    int ans = 0;
    int dx[] = {0, 0, 1, -1};
    int dy[] = {1, -1, 0, 0};
    
    // 寻找起点 '@' 并初始化队列
    void fun1() {
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (ca[i][j] == '@') {  // 修正为相等判断
                    ia[i][j] = 1;
                    ans = 1;
                    a.push({i, j});
                    return;  // 找到一个起点后退出,避免重复入队
                }
            }
        }
    }
    
    // BFS 遍历计算可达区域大小
    void fun() {
        while (!a.empty()) {
            st node = a.front();  // 修改变量名,避免与全局n冲突
            a.pop();
            for (int i = 0; i < 4; i++) {
                int xx = node.x + dx[i];
                int yy = node.y + dy[i];
                // 边界判断(使用全局n和m)
                if (xx <= 0 || xx > n || yy <= 0 || yy > m) continue;
                if (ca[xx][yy] == '#') continue;  // 障碍物判断
                if (ia[xx][yy]) continue;  // 已访问判断
                ia[xx][yy] = 1;
                a.push({xx, yy});
                ans++;
            }
        }
    }
    
    int main() {
        cin >> n >> m;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                cin >> ca[i][j];
            }
        }
        fun1();  // 只需调用一次寻找起点
        fun();   // 执行BFS
        cout << ans;
        return 0;
    }
    

    11小时前 来自 内蒙古

    0
  • 求解

    16小时前 来自 浙江

    0

热门讨论