Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define ULL unsigned long long
#define D double
#define pb push_back
#define mp make_pair
#define sf scanf
#define pf printf
#define ff first
#define ss second
#define SZ 100005
#define eps 1e-8
#define PI (2*acos(0.0))
#define mem(a, b) memset(a, b, sizeof a)
#define FastIO ios_base::sync_with_stdio(0)
const int inf = 0x7f7f7f7f;
int dx[] = {1,-1,0,0};
int dy[] = {0,0,1,-1};
//int dx[]={2,1,-1,-2,-2,-1,1,2};
//int dy[]={1,2,2,1,-1,-2,-2,-1};
//int mnth[]={-1,31,28,31,30,31,30,31,31,30,31,30,31};

int n, m;
char grid[205][205];
int seen[205][205], dist[205][205];

bool valid(int x, int y)
{
    if(x>=0 && x<n && y>=0 && y<m && seen[x][y]==0 && grid[x][y]!='#') return 1;
    return 0;
}

void bfs(int x, int y)
{
    mem(seen, 0);
    mem(dist, inf);
    seen[x][y] = 1;
    dist[x][y] = 0;

    queue<int>q;
    q.push(x); q.push(y);

    while(!q.empty())
    {
        x = q.front(); q.pop();
        y = q.front(); q.pop();

        for(int i=0; i<4; i++) {
            int xx = x + dx[i];
            int yy = y + dy[i];

            if(valid(xx, yy)) {
                seen[xx][yy] = 1;
                dist[xx][yy] = dist[x][y] + 1;
                q.push(xx); q.push(yy);
            }
        }
    }
}

int main()
{
    while(sf("%d %d", &n, &m)==2)
    {
        for(int i=0; i<n; i++) {
            sf("%s", grid[i]);
        }

        for(int i=0; i<n; i++) {
            for(int j=0; j<m; j++) {
                if(grid[i][j]=='%') {
                    bfs(i, j);
                    break;
                }
            }
        }

        int princes = 0, solder = inf;

        for(int i=0; i<n; i++) {
            for(int j=0; j<m; j++) {
                if(grid[i][j]=='@') {
                    princes = dist[i][j];
                }

                else if(grid[i][j]=='$') {
                    solder = min(solder, dist[i][j]);
                }
            }
        }

        //cout<<princes<<" "<<solder<<endl;
        if(solder<=princes) pf("No\n");
        else pf("Yes\n");
    }
    //main();
    return 0;
}