Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;

using P = std::pair<int, int>;


vector<vector<int>> bfs(vector<string> const& v, int y, int x) {
    vector<vector<int>> d(v.size(), vector<int>(v[0].size(), 1e9));
    d[y][x] = 0;
    queue<P> que;
    que.push(P{y, x});
    while(!que.empty()) {
        P p = que.front(); que.pop();
        int dx[4] = {0, 1, 0, -1},
            dy[4] = {1, 0, -1, 0};
        for(int i=0; i<4; ++i) {
            int ny = p.first + dy[i], nx = p.second + dx[i];
            if(0 <= ny && ny < v.size() && 0 <= nx && nx < v[0].size() && v[ny][nx] != '#' && d[ny][nx] == 1e9) {
                que.push(P{ny, nx});
                d[ny][nx] = d[p.first][p.second] + 1;
            }
        }
    }
    return d;
}

int main() {
    int H, W;
    cin >> H >> W;
    vector<string> v(H);
    for(int i=0; i<H; ++i) {
        cin >> v[i];
    }
    vector<vector<int>> d;
    for(int i=0; i<H; ++i) {
        for(int j=0; j<W; ++j) {
            if(v[i][j] == '%') {
                d = bfs(v, i, j);
            }
        }
    }
    int p=0, s=1e9;
    for(int i=0; i<H; ++i) {
        for(int j=0; j<W; ++j) {
            if(v[i][j] == '@') {
                p = d[i][j];
            }
            if(v[i][j] == '$') {
                s = min(s, d[i][j]);
            }
        }
    }
    if(s <= p) {
        cout << "No" << endl;
    } else {
        cout << "Yes" << endl;
    }
}