Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <bits/stdc++.h>
#define endl "\n"
using namespace std;
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
template<class T>
inline bool chmax(T &a, T b) {
    if(a < b) {
        a = b;
        return true;
    }
    return false;
}

template<class T>
inline bool chmin(T &a, T b) {
    if(a > b) {
        a = b;
        return true;
    }
    return false;
}

const long long INF = 1e18;
//const ll mod = 1000000007;
ll H, W;
string field[500];
ll sh, sw;
ll dh[4] = {1, -1, 0, 0};
ll dw[4] = {0, 0, 1, -1};
ll dist[500][500];


int main() {
    cin >> H >> W;
    for(int h = 0; h < H; h++) {
        cin >> field[h];
        for(int w = 0; w < W; w++) {
            if(field[h][w] == '%') {
                sh = h;
                sw = w;
            }
            dist[h][w] = INF;
        }
    }
    dist[sh][sw] = 0;
    queue<i_i> que;
    que.push({sh, sw});
    while(!que.empty()) {
        auto tmp = que.front();
        que.pop();
        int fromh = tmp.first;
        int fromw = tmp.second;
        for(int k = 0; k < 4; k++) {
            int toh = fromh + dh[k];
            int tow = fromw + dw[k];
            if(toh >= H or toh < 0) continue;
            if(tow >= W or tow < 0) continue;
            if(field[toh][tow] == '#') continue;
            ll c = dist[fromh][fromw] + 1;
            if(chmin(dist[toh][tow], c)) que.push({toh, tow});
        }
    }
    ll q;
    for(int h = 0; h < H; h++) {
        for(int w = 0; w < W; w++) {
            if(field[h][w] == '@') q = dist[h][w];
        }
    }
    string ans = "Yes";
    for(int h = 0; h < H; h++) {
        for(int w = 0; w < W; w++) {
            if(field[h][w] != '$') continue;
            if(dist[h][w] <= q) ans = "No";
        }
    }
    cout << ans << endl;
    return 0;
}