血色先锋队【BFS】

题目大意:

给出 k 个起始点和 t 个结束点,求每个结束点距离任意一个起始点的最短马哈顿距离。
I n p u t

5 4 2 3
1 1
5 4
3 3
5 3
2 4

O u t p u t

3
1
3

思路:

裸的 B F S ,读入每个起始点的位置后就可以求出图中每一个点的最短马哈顿距离,求完之后再读入终点, O ( 1 ) 输出即可。
时间复杂度: O ( n m )


代码:

#include <cstdio>
#include <iostream>
using namespace std;

const int dx[]={0,0,0,-1,1};
const int dy[]={0,1,-1,0,0};
int n,m,k,t,x,y,a[1011][1011],state[10000011][5],head,tail,dis[1011][1011];

void bfs() 
{
    do
    {
        head++;
        for (int i=1;i<=4;i++)
        {
            int xx=state[head][1]+dx[i];
            int yy=state[head][2]+dy[i];
            if (a[xx][yy]||xx<1||xx>n||yy<1||yy>m) continue;  //出界或已经到达
            tail++;
            a[xx][yy]=1;
            state[tail][1]=xx;
            state[tail][2]=yy;
            dis[xx][yy]=dis[state[head][1]][state[head][2]]+1;  //记录最短距离
        }
    }
    while (head<tail);
}

int main()
{
    scanf("%d%d%d%d",&n,&m,&k,&t);
    for (int i=1;i<=k;i++)
    {
        scanf("%d%d",&x,&y);
        tail++;
        state[tail][1]=x;
        state[tail][2]=y;
        a[x][y]=1;
    }
    bfs();
    for (int i=1;i<=t;i++)
    {
        scanf("%d%d",&x,&y);
        printf("%d\n",dis[x][y]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/SSL_ZYC/article/details/81321433
BFS