Problem: Example

Input

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


Output

Yes

Solution (in CPP):

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

using namespace std;
#define pii pair<int, int>
#define tii tuple<int, int, int>

int dy[4] = {-1, 0, 1, 0};
int dx[4] = { 0, 1, 0,-1};
queue<pii> que;

int main(void){
    int h, w;
    cin >> h >> w;
    vector<string> s(h);
    for (int i = 0; i < h; i++) cin >> s[i];
    vector<vector<int> > g(h, vector<int>(w, 1e9));
    
    int py, px, hy, hx;
    for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) 
        if (s[i][j] == '$') que.push(make_pair(i,j)), g[i][j] = 0;
        else if (s[i][j] == '@') py = i, px = j;
        else if (s[i][j] == '%') hy = i, hx = j;
        else if (s[i][j] == '#') g[i][j] = -1;
        
    while (!que.empty()) {
        pii p = que.front(); que.pop();
        int ty = p.first, tx = p.second, node = g[ty][tx];
        for (int i = 0; i < 4; i++) {
            int ny = ty + dy[i];
            int nx = tx + dx[i];
            if (ny < 0 || ny >= h || nx < 0 || nx >= w || g[ny][nx] == -1) continue;
            if (g[ny][nx] > node+1) {
                g[ny][nx] = node+1;
                que.push(make_pair(ny,nx));
            }
        }
    }
    int sol = g[hy][hx];
    
    g[py][px] = 0;
    que.push(make_pair(py,px));
    while (!que.empty()) {
        pii p = que.front(); que.pop();
        int ty = p.first, tx = p.second, node = g[ty][tx];
        for (int i = 0; i < 4; i++) {
            int ny = ty + dy[i];
            int nx = tx + dx[i];
            if (ny < 0 || ny >= h || nx < 0 || nx >= w || g[ny][nx] == -1) continue;
            if (g[ny][nx] > node+1) {
                g[ny][nx] = node+1;
                que.push(make_pair(ny,nx));
            }
        }
    }
    if (sol == g[hy][hx]) cout << "No" << endl;
    else cout << "Yes" << endl;
}