Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <bits/stdc++.h>
#define rep(i, a, n) for(int i = a; i < n; i++)
#define REP(i, n) rep(i, 0, n)
#define repb(i, a, b) for(int i = a; i >= b; i--)
#define all(a) a.begin(), a.end()
#define int long long
#define chmax(x, y) x = max(x, y)
#define chmin(x, y) x = min(x, y)
using namespace std;
typedef pair<int, int> P;
const int mod = 1000000007;
const int INF = 1e12;

int h, w;
char s[210][210];
int d[210][210];
int dy[4] = {1, -1, 0, 0};
int dx[4] = {0, 0, 1, -1};
bool contain(int y, int x){
   return (0 <= y && y < h && 0 <= x && x < w);
}

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin >> h >> w;
    int sy = 0, sx = 0;
    rep(i, 0, h){
        rep(j, 0, w){
            cin >> s[i][j];
            if(s[i][j] == '%'){
                sy = i; sx = j;
            }
        }
    }
    rep(i, 0, h) rep(j, 0, w) d[i][j] = INF;
    d[sy][sx] = 0;
    queue<P> q;
    q.push(P(sy, sx));
    while(!q.empty()){
        P p = q.front(); q.pop();
        int y = p.first;
        int x = p.second;
        rep(i, 0, 4){
            int ny = y + dy[i];
            int nx = x + dx[i];
            if(!contain(ny, nx) || d[ny][nx] != INF || s[ny][nx] == '#') continue;
            d[ny][nx] = d[y][x] + 1;
            q.push(P(ny, nx));
        }
    }
    int MIN = INF, princess;
    rep(i, 0, h){
        rep(j, 0, w){
            if(s[i][j] == '@') princess = d[i][j];
            else if(s[i][j] == '$') chmin(MIN, d[i][j]);
        }
    }
    if(princess < MIN) cout << "Yes" << endl;
    else cout << "No" << endl;
}