Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <algorithm>
#include <iostream>
#include <vector>
#include <math.h>
#include <set>
#include <map>
#include <string>
#include <stack>
#include <queue>
#include <iomanip>
#include <numeric>
#include <tuple>
#include <bitset>
#include <complex>
#include <unistd.h>
#include <cassert>
#include <cctype>
#include <random>
#define _USE_MATH_DEFINES
#define _GLIBCXX_DEBUG
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> plglg;
typedef tuple<int, int, int> tiii;
typedef tuple<ll, ll, ll> tlglglg;
typedef complex<double> xy_t;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
double pi = 3.141592653589793;
ll mod = 1000000007;
int intmax = 2147483647;
int intmin = -2147483648;
ll llmax = 9223372036854775807;
ll llmin = -9223372036854775807;
int iinf = intmax / 8;
ll inf = llmax / 8;
double eps = 1e-11;

int H, W;
int bo[210][210];
ll d[210][210];

void BFS(int x, int y) {
    for (int i = 0; i < H; i++) {
        fill(d[i], d[i] + W + 10, llmax);
    }
    queue<pii> que;
    d[x][y] = 0;
    que.push(pii(x, y));
    while (que.size() > 0) {
        pii p = que.front();
        int xx = p.first;
        int yy = p.second;
        que.pop();
        for (int i = 0; i < 4; i++) {
            int xxx = xx + dx[i];
            int yyy = yy + dy[i];
            if (xxx >= 0 && xxx < H && yyy >= 0 && yyy < W) {
                if (d[xxx][yyy] == llmax && bo[xxx][yyy] > 0) {
                    d[xxx][yyy] = d[xx][yy] + 1;
                    que.push(pii(xxx, yyy));
                }
            }
        }
    }
}

int main() {
    cin >> H >> W;
    int st[2];
    for (int i = 0; i < H; i++) {
        string s;
        cin >> s;
        char mark[5] = {'#', '.', '@', '$', '%'};
        for (int j = 0; j < W; j++) {
            for (int k = 0; k < 5; k++) {
                if (s[j] == mark[k]) {
                    bo[i][j] = k;
                    if (k == 4) {
                        st[0] = i;
                        st[1] = j;
                    }
                }
            }
        }
    }
    BFS(st[0], st[1]);
    ll pri = llmax;
    ll sol = llmax;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            if (bo[i][j] == 2) {
                pri = d[i][j];
                //cout << pri << " aaa" << endl;
            } else if (bo[i][j] == 3) {
                //cout << d[i][j] << endl;
                if (d[i][j] < sol) {
                    sol = d[i][j];
                }
            }
        }
    }
    if (pri < sol) {
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }
}