Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <tuple>

using namespace std;

const int INF = 1 << 30;

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

int main() {
    int H, W;
    cin >> H >> W;

    vector<string> S(H);
    for (auto& s : S) cin >> s;

    int sx, sy;
    for (int x = 0; x < H; ++x) {
        for (int y = 0; y < W; ++y) {
            if (S[x][y] == '%') {
                sx = x;
                sy = y;
            }
        }
    }

    queue<pair<int, int>> que;
    que.emplace(sx, sy);
    vector<vector<int>> dist(H, vector<int>(W, INF));
    dist[sx][sy] = 0;

    while (!que.empty()) {
        int x, y;
        tie(x, y) = que.front();
        que.pop();

        for (int i = 0; i < 4; ++i) {
            int nx = x + dx[i], ny = y + dy[i];
            if (nx < 0 || H <= nx || ny < 0 || W <= ny ||
                S[nx][ny] == '#' || dist[nx][ny] < INF) continue;

            dist[nx][ny] = dist[x][y] + 1;
            que.emplace(nx, ny);
        }
    }

    int pri, sol = INF;
    for (int x = 0; x < H; ++x) {
        for (int y = 0; y < W; ++y) {
            if (S[x][y] == '@') {
                pri = dist[x][y];
            } else if (S[x][y] == '$') {
                sol = min(sol, dist[x][y]);
            }
        }
    }

    cout << (pri < sol ? "Yes" : "No") << endl;
    return 0;
}