Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <cstdio>
#include <cstring>

#include <queue>

using namespace std;

struct Info {
    int x, y, dis;
};

const int MAXN = 205;
const int DIFF[2][4] = {{0, 0, 1, -1}, {1, -1, 0, 0}};

int n, m;
char mp[MAXN][MAXN];
bool vis[MAXN][MAXN];

int main() {
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++) {
        scanf("%s", mp[i] + 1);
    }

    queue<Info> q;
    int dis1 = 1e9;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            if (mp[i][j] == '@') {
                q.push((Info) {i, j, 0});
                break;
            }
        }
        if (!q.empty()) break;
    }
    while (!q.empty()) {
        Info info = q.front(); q.pop();
        if (mp[info.x][info.y] == '%') {
            dis1 = info.dis;
            break;
        }
        for (int i = 0; i < 4; i++) {
            int nx = info.x + DIFF[0][i], ny = info.y + DIFF[1][i];
            if (nx < 1 || nx > n || ny < 1 || ny > m) continue;
            if (mp[nx][ny] == '#') continue;
            if (vis[nx][ny]) continue;
            q.push((Info) {nx, ny, info.dis + 1});
            vis[nx][ny] = true;
        }
    }
    while (!q.empty()) q.pop();

    memset(vis, 0, sizeof(vis));
    int dis2 = 1e9;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            if (mp[i][j] == '$') {
                q.push((Info) {i, j, 0});
            }
        }
    }
    while (!q.empty()) {
        Info info = q.front(); q.pop();
        if (mp[info.x][info.y] == '%') {
            dis2 = info.dis;
            break;
        }
        for (int i = 0; i < 4; i++) {
            int nx = info.x + DIFF[0][i], ny = info.y + DIFF[1][i];
            if (nx < 1 || nx > n || ny < 1 || ny > m) continue;
            if (mp[nx][ny] == '#') continue;
            if (vis[nx][ny]) continue;
            q.push((Info) {nx, ny, info.dis + 1});
            vis[nx][ny] = true;
        }
    }

    puts(dis1 < dis2 ? "Yes" : "No");
    return 0;
}