0分求助BFS
查看原帖
0分求助BFS
1094441
封禁用户楼主2024/3/30 16:14
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;

int fx, fy;
int n, m, a, b;
int _map[505][505];
bool vis[505][505];
int dx[5] = {0, 0, 0, -1, 1};
int dy[5] = {0, 1, -1, 0, 0};

struct node
{
    int x, y, t;
};

void bfs()
{
    queue<node> q;
    q.push((node){fx, fy, 0});
    vis[fx][fy] = true;
    while (!q.empty())
    {
        node ls = q.front();
        q.pop();
        for (int i = 1; i <= 4; ++i)
        {
            int tx = ls.x + dx[i];
            int ty = ls.y + dy[i];
            int tt = ls.t + 1;
            if (tx >= 1 && tx <= n && ty >= 1 && ty <= m && !vis[tx][ty])
            {
                vis[tx][ty] = true;
                _map[tx][ty] = min(tt, _map[tx][ty]);
                q.push((node){tx, ty, tt});
            }
        }
    }
}

int main()
{
    cin >> n >> m >> a >> b;
    for (int i = 1; i <= n; ++ i) 
	{
    	for (int j = 1; j <= m; ++ j) 
		{
        	_map[i][j] = 0x7fffffff;
    	}
	}
	
    for (int i = 1; i <= a; ++i)
    {
        cin >> fx >> fy;
        _map[fx][fy] = 1;
        bfs();
    }
    for (int i = 1; i <= b; ++i)
    {
        int x, y;
        cin >> x >> y;
        cout << _map[x][y] << endl;
    }
    return 0;
}
2024/3/30 16:14
加载中...