Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <iostream>
#include <queue>
#include <stack>
#include <vector>
#include <cassert>
#include <cmath>
#include <numeric>
#include <algorithm>
#include <iomanip>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>

using namespace std;
using ll = long long;
using pii = pair<int, int>;

constexpr int dir[] = {1, 0, -1, 0, 1};

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

    auto in = [=](const int h, const int w) {
        return h >= 0 and h < H and w >= 0 and w < W;
    };

    vector<vector<char>> field(H, vector<char>(W));
    pii s;
    pii g;
    vector<pii> sol;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            cin >> field[i][j];
            if (field[i][j] == '@') {
                s = make_pair(i, j);
                field[i][j] = '.';
            } else if (field[i][j] == '%') {
                g = make_pair(i, j);
                field[i][j] = '.';
            } else if (field[i][j] == '$') {
                sol.push_back(make_pair(i, j));
                field[i][j] = '.';
            }
        }
    }
    constexpr int INF = 1 << 30;
    vector<vector<int>> dist(H, vector<int>(W, INF));
    queue<pair<pii, int>> q;
    dist[g.first][g.second] = 0;
    q.push(make_pair(g, 0));
    while (not q.empty()) {
        const auto p = q.front();
        q.pop();
        for (int d = 0; d < 4; d++) {
            const int newy = p.first.first + dir[d];
            const int newx = p.first.second + dir[d + 1];
            if (in(newy, newx) and field[newy][newx] == '.' and dist[newy][newx] == INF) {
                dist[newy][newx] = p.second + 1;
                q.push(make_pair(make_pair(newy, newx), p.second + 1));
            }
        }
    }
    for (const auto& pos : sol) {
        if (dist[s.first][s.second] >= dist[pos.first][pos.second]) {
            cout << "No" << endl;
            return 0;
        }
    }
    cout << "Yes" << endl;


    return 0;
}