Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <bits/stdc++.h>
using namespace std;


//#define cin2(a,b) scanf("%d%lf",&a,&b)
#define pb push_back
#define all(x) x.begin(),x.end()
#define dist(x1,y1,x2,y2) (x1-x2)*1LL*(x1-x2)+(y1-y2)*1LL*(y1-y2)
#define ll long long
#define db double
#define ull unsigned ll
#define lb lower_bound
#define inf 1e9
#define mp make_pair
#define gcd(x,y) __gcd(x,y);
#define pii pair<int,int>
#define M 1000000007
#define pi acos(-1)


const int mx = 202;
int soldier[mx][mx],prince[mx][mx];
char s[mx][mx];
int r, c;
bool memo[mx][mx];;

int dx[] = {1,-1,0,0};
int dy[] = {0,0,1,-1};


bool process()
{
    int i,j,k;
    queue<pair<pii,int> > q;
    for(i=0;i<r;i++) {
        for(j=0;j<c;j++) {
            memo[i][j] = false;
            soldier[i][j] = inf;
            prince[i][j] = inf;
            if(s[i][j]=='@') {
                memo[i][j] = true;
                q.push(mp(mp(i,j),0));
                prince[i][j] = 0;
            }
        }
    }
    while(!q.empty()) {
        pair<pii,int> tmp = q.front();
        q.pop();
        int x = tmp.first.first;
        int y = tmp.first.second;
        int v = tmp.second;
        prince[x][y] = v;
        for(i=0;i<4;i++) {
            int tx = x + dx[i];
            int ty = y + dy[i];
            if(tx<0||tx==r||ty<0||ty==c) continue;
            if(memo[tx][ty]) continue;
            if(s[tx][ty]=='#') continue;
            memo[tx][ty] = true;
            q.push(mp(mp(tx,ty),v+1));
        }
    }
    while(!q.empty()) q.pop();
    for(i=0;i<r;i++) {
        for(j=0;j<c;j++) {
            memo[i][j] = false;
            if(s[i][j]=='$') {
                memo[i][j] = true;
                q.push(mp(mp(i,j),0));
            }
        }
    }
    while(!q.empty()) {
        pair<pii,int> tmp = q.front();
        q.pop();
        int x = tmp.first.first;
        int y = tmp.first.second;
        int v = tmp.second;
        soldier[x][y] = v;
        for(i=0;i<4;i++) {
            int tx = x + dx[i];
            int ty = y + dy[i];
            if(tx<0||tx==r||ty<0||ty==c) continue;
            if(s[tx][ty]=='#') continue;
            if(memo[tx][ty]) continue;
            memo[tx][ty] = true;
            q.push(mp(mp(tx,ty),v+1));
        }
    }

    for(i=0;i<r;i++) {
        //printf("%s\n",s[i]);
        for(j=0;j<c;j++) {
            if(s[i][j]=='%') {
                //printf("i = %d j = %d\n",soldier[i][j],prince[i][j]);
                return soldier[i][j]>prince[i][j];
            }
        }
        //printf("\n");
    }
    return false;
}



int main()
{
    while(true) {
        int i,j,k;
        scanf("%d%d",&r,&c);
        for(i=0;i<r;i++) scanf("%s",s[i]);

        int ans = process();
        if(ans) printf("Yes\n");
        else printf("No\n");
        break;
    }
}