Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cctype>
#include<math.h>
#include<string>
#include<string.h>
#include<stack>
#include<queue>
#include<vector>
#include<utility>
#include<set>
#include<map>
#include<stdlib.h>
#include<iomanip>

using namespace std;

#define ll long long
#define ld long double
#define EPS 0.0000000001
#define INF 1e9
#define MOD 1000000007
#define rep(i,n) for(int i=0;i<(n);i++)
#define loop(i,a,n) for(i=a;i<(n);i++)
#define all(in) in.begin(),in.end()
#define shosu(x) fixed<<setprecision(x)

typedef vector<int> vi;
typedef vector<string> vs;
typedef pair<int,int> pii;

int gcd(int a, int b){
    if(b==0) return a;
    return gcd(b,a%b);
}
int lcm(int a, int b){
    return a*b/gcd(a,b);
}

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

int main(void) {
    int i,j;
    int h,w;
    cin >> h >> w;
    vs s(h);
    rep(i,h)cin >> s[i];
    int dist[200][200];
    rep(i,h)rep(j,w)dist[i][j] = INF;
    rep(sx,h)rep(sy,w) if(s[sx][sy] =='%'){
        dist[sx][sy] = 0;
        queue<pii> q;
        q.push(pii(sx,sy));
        vi ans(2,INF);
        while(q.size()){
            int x = q.front().first;
            int y = q.front().second;
            if(s[x][y] == '@' || s[x][y] == '$'){
                ans[s[x][y]=='@'] = min(ans[s[x][y]=='@'], dist[x][y]);
            }
            q.pop();
            rep(i,4){
                int nx = x + dx[i];
                int ny = y + dy[i];
                if(0 > nx || 0 > ny || nx >= h || ny >= w)continue;
                if(s[nx][ny] == '#')continue;
                if(dist[nx][ny] > dist[x][y] + 1){
                    dist[nx][ny] = dist[x][y] + 1;
                    q.push(pii(nx,ny));
                }
            }
        }
        if(ans[1] < ans[0]) cout << "Yes" << endl;
        else cout << "No" << endl;
        break;
    }
}