Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <algorithm>
#include <bitset>
#include <complex>
#include <cstdio>
#include <cstdint>
#include <cassert>
#include <cmath>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <tuple>
#include <utility>
#include <vector>
using namespace std;

using int64 = int64_t;

constexpr int64 MOD = 1000000007;

constexpr int INF = 1 << 29;

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

/*
 * @ princess
 * $ soldier
 * % hatch
 * . empty
 * # wall
 */

struct S {
    int x, y, dist;
    S() {}
    S(int a, int b, int c): x(a), y(b), dist(c) {}
};

int H, W;
string arr[222];

int visited[222][222];

int p_dist = INF;
int s_dist = INF;

void dfs(int x, int y, int dist = 0) {
    visited[x][y] = true;
    if (arr[x][y] == '@') {
        s_dist = dist;
    } else if (arr[x][y] == '$') {
        p_dist = min(p_dist, dist);
    }
    for (int j = 0; j < 4; ++j) {
        int nx = x + dx[j], ny = y + dy[j];
        if (nx < 0 || H <= nx || ny < 0 || W <= ny) { continue; }
        if (arr[nx][ny] != '#' && !visited[nx][ny]) {
            dfs(nx, ny, dist+1);
        }
    }
}

int main() {
    cin >> H >> W;
    for (int j = 0; j < H; ++j) {
        cin >> arr[j];
    }
    for (int j = 0; j < H; ++j) { fill(visited[j], visited[j]+W, 0); }


    int sx, sy;
    
    for (int j = 0; j < H; ++j) {
        int val = arr[j].find('%');
        if (val != -1) {
            sx = j; sy = val;
            break;
        }
    }


    const string result = [&]() {
        int p_dist = INF;
        int s_dist = INF;
        queue<S> que;
        que.emplace(sx, sy, 0);
        visited[sx][sy] = true;
        while (!que.empty()) {
            S p = que.front(); que.pop();
            int x = p.x, y = p.y;
            if (arr[x][y] == '@') {
                p_dist = p.dist;
            } else if (arr[x][y] == '$') {
                s_dist = min(s_dist, p.dist);
            }
            if (p_dist < p.dist) {
                break;
            }
            for (int j = 0; j < 4; ++j) {
                int nx = x + dx[j], ny = y + dy[j];
                if (nx < 0 || H <= nx || ny < 0 || W <= ny) { continue; }
                if (arr[nx][ny] != '#' && !visited[nx][ny]) {
                    visited[nx][ny] = true;
                    que.emplace(nx, ny, p.dist+1);
                }
            }
        }
        return p_dist < s_dist ? "Yes" : "No";
    }();

    cout << result << endl;
    return 0;
}