Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <utility>
#include <cstring>
#include <iomanip>
#include <numeric>
#include <cmath>
#include <queue>
#include <map>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int INF = 1<<30; 
const int MOD = 1e9 + 7;
const int dy[] = {1, 0, -1, 0};
const int dx[] = {0, 1, 0, -1};
const int MAX_N = 210;
int h, w;
char field[MAX_N][MAX_N];
int table[MAX_N][MAX_N];
int princess;
int soldier = INF;
void bfs(int y, int x)
{
    table[y][x] = 0;
    queue<P> que;
    que.push(P(y, x));
    while(!que.empty())
    {
        P p = que.front(); que.pop();
        for(int i = 0; i < 4; i++)
        {
            int ny = p.first + dy[i];
            int nx = p.second + dx[i];
            if(ny < 0 || nx < 0 || ny >= h || nx >= w) continue;
            if(table[ny][nx] >= 0 || field[ny][nx] == '#') continue;
            table[ny][nx] = table[p.first][p.second] + 1;
            if(field[ny][nx] == '@') princess = table[ny][nx];
            if(field[ny][nx] == '$') soldier = min(table[ny][nx], soldier);
            que.push(P(ny, nx));
        }
    }
}
int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    cin >> h >> w;
    int sy, sx;
    memset(table, - 1, sizeof(table));
    for(int i = 0; i < h; i++)
    {
        for(int j = 0; j < w; j++) 
        {
            cin >> field[i][j];
            if(field[i][j] == '%') sy = i, sx = j;
        }
    }
    bfs(sy, sx);
    cout << (princess < soldier ? "Yes" : "No") << endl;
    return 0;
}