bfs 40pts 求大佬调调
  • 板块P1141 01迷宫
  • 楼主coool
  • 当前回复5
  • 已保存回复5
  • 发布时间2023/9/2 18:06
  • 上次更新2023/11/2 23:50:24
查看原帖
bfs 40pts 求大佬调调
526922
coool楼主2023/9/2 18:06
#include <bits/stdc++.h>
using namespace std;

int n, m;
int a[1005][1005];
int vis[1005][1005];
int f[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};

bool check(int x, int y, int k)
{
    if (x < 1 || y < 1 || x > n || y > n || vis[x][y] || a[x][y] != k ^ 1)
        return false;
    return true;
}

int bfs(int x, int y)
{
    queue<pair<int, int>> q;
    int cnt = 0;
    q.push({x, y});

    while (!q.empty())
    {
        auto it = q.front();
        q.pop();

        for (int i = 0; i < 4; i++)
        {
            int xx = it.first + f[i][0];
            int yy = it.second + f[i][1];

            int k = a[it.first][it.second];
            if (check(xx, yy, k))
            {
                cnt++;
                vis[xx][yy] = 1;
                q.push({xx,yy});
            }
        }
    }

    return cnt;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    cin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        string s;
        cin >> s;
        for (int j = 1; j <= n; j++)
        {
            a[i][j] = s[j - 1] - '0';
        }
    }

    while (m--)
    {
        int x, y;
        cin >> x >> y;
        memset(vis, 0, sizeof(vis));

        cout << bfs(x, y) << endl;
    }
    return 0;
}
2023/9/2 18:06
加载中...