Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef pair<ll, ll> P;

#define EACH(i, a) for(auto&& i:a)
#define FOR(i,a,b) for(ll i = (a); i < (b); ++i)
#define RFOR(i,a,b) for(ll i = (b)-1; i >= (a); --i)
#define REP(i,n) FOR(i,0,n)
#define RREP(i,n) RFOR(i,0,n)
#define pb push_back
#define ALL(v) (v).begin(),(v).end()

const ll linf = 1e18;
const ll inf = 1e9;

template<class T>
istream& operator>>(istream& is, vector<T>& vec) {
    EACH(x,vec) is >> x;
    return is;
}

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

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int H, W; cin >> H >> W;
    auto inRange = [&](int x, int y) {
        return 0 <= x && x < W && 0 <= y && y < H;
    };
    vector<string> m(H); cin >> m;
    int gx = -1, gy = -1;
    REP(y, H) REP(x, W) if (m[y][x] == '%') {
        gx = x, gy = y;
    }
    vector<vector<ll>> dist(H, vector<ll>(W, -1));
    queue<P> Q; Q.push({gx, gy});
    while ( !Q.empty() ) {
        P p = Q.front(); Q.pop();
        ll x, y; tie(x, y) = p;
        REP(d, 4) {
            ll nx = x + dx[d];
            ll ny = y + dy[d];
            if ( inRange(nx, ny) && m[ny][nx] != '#' && dist[ny][nx] < 0 ) {
                dist[ny][nx] = dist[y][x]+1;
                Q.push({nx, ny});
            }
        }
    }
    ll sdist = linf, pdist = linf;
    REP(y, H) REP(x, W) {
        if (m[y][x] == '$') {
            sdist = min(sdist, dist[y][x]);
        }
        if (m[y][x] == '@') {
            pdist = min(pdist, dist[y][x]);
        }
    }
    if (pdist == linf || pdist >= sdist) {
        cout << "No" << endl;
    }
    else {
        cout << "Yes" << endl;
    }
}