Problem: Example

Input

2 4
%.@\$
..\$\$


Output

Yes

Solution (in CPP):

Solution:
# include <iostream>
# include <cstdio>
# include <cstring>
using namespace std;
struct node
{
    int x, y;
}q[80000];
int n, m, dis[206][206];
char s[206][206];
int sol, girl;
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
void bfs(int ex, int ey)
{
    int l=0, r=0;
    q[r++] = node{ex, ey};
    dis[ex][ey] = 0;
    while(l < r)
    {
        node u = q[l++];
        for(int i=0; i<4; ++i)
        {
            int mx = u.x + dx[i];
            int my = u.y + dy[i];
            if(mx < 0 || mx >= n || my < 0 || my >= m || s[mx][my] == '#' || dis[mx][my] != -1) continue;
            dis[mx][my] = dis[u.x][u.y] + 1;
            q[r++] = node{mx, my};
            if(s[mx][my]=='$')
                sol = min(sol, dis[mx][my]);
            else if(s[mx][my] == '@')
                girl = dis[mx][my];
        }
    }
}
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        sol = girl = 1e9;
        memset(dis, -1, sizeof(dis));
        for(int i=0; i<n; ++i)
            scanf("%s",s[i]);
        for(int i=0; i<n; ++i)
        {
            for(int j=0; j<m; ++j)
            {
                if(s[i][j] == '%')
                {
                    bfs(i,j);
                    break;
                }
            }
        }
        //printf("%d %d\n",sol,girl);
        if(sol > girl || (sol == 1e9&&girl!=1e9))
           puts("Yes");
        else
            puts("No");
    }
    return 0;
}