ABC405D题解

首先一看就知道要先跑多源最短路,然后标箭头就相当于找最短路,其实可以用 \(d_{r,c} = d_{i,j}-1\) 来判断对于 \((i,j)\)\((r,c)\) 这个位置是否是最短路,然后就可以确定箭头方向了。
代码:

#include<bits/stdc++.h>
using namespace std;
const int N = 1005;
int d[N][N];
char a[N][N];
struct node
{
    int x;
    int y;
    int cnt;
};
int dx[] = {0,0,-1,1};
int dy[] = {-1,1,0,0};
char s[] = {'<','>','^','v'};
char b[N][N];
signed main()
{
    int n,m;
    scanf("%d %d",&n,&m);
    for(int i = 1;i<=n;i++)
    {
        scanf("%s",a[i]+1);
    }
    memset(d,0x3f,sizeof(d));
    queue<node>q;
    for(int i = 1;i<=n;i++)
    {
        for(int j = 1;j<=m;j++)
        {
            if(a[i][j] == 'E')
            {
                q.push({i,j,0});
                d[i][j] = 0;
            }
        }
    }
    while(q.size())
    {
        node num = q.front();
        q.pop();
        for(int i = 0;i<4;i++)
        {
            int r = num.x+dx[i];
            int c = num.y+dy[i];
            if(r>=1&&c>=1&&r<=n&&c<=m&&a[r][c]!='#'&&d[r][c]>d[num.x][num.y]+1)
            {
                d[r][c] = d[num.x][num.y]+1;
                q.push({r,c,d[r][c]});
            }
        }
    }
    for(int i = 1;i<=n;i++)
    {
        for(int j = 1;j<=m;j++)
        {
            b[i][j] = a[i][j];
            for(int k = 0;k<4;k++)
            {
                int r = i+dx[k];
                int c = j+dy[k];
                if(r>=1&&c>=1&&r<=n&&c<=m&&a[r][c]!='#'&&d[r][c] == d[i][j]-1)
                {
                    b[i][j] = s[k];
                    break;
                }
            }
            printf("%c",b[i][j]);
        }
        printf("\n");
    }
    return 0;
}
posted @ 2025-05-13 21:26  林晋堃  阅读(18)  评论(0)    收藏  举报