bfs记忆化,一个点都不对,d了一天d不出来

P1141 01迷宫

Lzx555 @ 2023-11-27 20:00:07

#include<iostream>
#include<queue>
using namespace std;
int map[1010][1010];
int allmap[1010][1010];
char arr[1010][1010];
int dx[4] = { 0,1,0,-1 };
int dy[4] = { 1,0,-1,0 };
int n, m;
int ans = 1;
struct node
{
    int x;
    int y;
}p1, p2;
queue<node> q;

int main()
{
    cin >> n >> m;
    getchar();
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            arr[i][j] = getchar();
        }
        getchar();
    }
    while (m--)
    {
        int x1, y1;
        cin >> x1 >> y1;
        p1.x = x1 - 1;
        p1.y = y1 - 1;
        if (allmap[p1.x][p1.y]!=0)
        {
            cout << allmap[p1.x][p1.y];
            continue;
        }
        q.push(p1);
        map[p1.x][p1.y] = 1;
        while (q.size() != 0)
        {
            p1 = q.front();
            q.pop();
            for (int i = 0; i < 4; i++)
            {
                p2.x = p1.x + dx[i];
                p2.y = p1.y + dy[i];
                if (p2.x >= 0 && p2.x < n && p2.y >= 0 && p2.y < n && map[p2.x][p2.y] == 0 && (arr[p1.x][p1.y] != arr[p2.x][p2.y]))
                {
                    q.push(p2);
                    map[p2.x][p2.y] = 1;
                    ans++;
                }
            }
        }
        cout << ans << endl;
        for (int i = 0; i < n; i++)//重置地图
        {
            for (int j = 0; j < n; j++)
            {
                cout << map[i][j];
                if (map[i][j] == 1)
                {
                    allmap[i][j] =ans;
             //记忆化搜索
                    map[i][j] = 0;
                }

            }
            cout << endl;
        }
        ans = 1;

    }
}

|