Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <bits/stdc++.h>

using namespace std;

#define LL long long
#define pii pair<int, int>
#define MP make_pair
#define ls i << 1
#define rs ls | 1
#define md (ll + rr >> 1)
#define lson ll, md, ls
#define rson md + 1, rr, rs
#define mod 1000000007
#define inf 0x3f3f3f3f
#define Pi acos(-1.0)
#define eps 1e-12
#define N 220
#define M 400020

char s[N][N];
int sx, sy;
int n, m;
int d[N][N];

int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};

bool in(int x, int y) {
	return x >= 1 && y >= 1 && x <= n && y <= m && s[x][y] != '#';
}

void bfs() {
	queue<int> q;
	q.push(sx); q.push(sy);
	memset(d, -1, sizeof d);
	d[sx][sy] = 0;
	while(!q.empty()) {
		int x = q.front(); q.pop();
		int y = q.front(); q.pop();
		for(int i = 0; i < 4; ++i) {
			int dx = x + dir[i][0];
			int dy = y + dir[i][1];
			if(!in(dx, dy)) continue;
			if(d[dx][dy] == -1) {
				d[dx][dy] = d[x][y] + 1;
				q.push(dx); q.push(dy);
			}
		}
	}
}

int main() {
	scanf("%d%d", &n, &m);
	for(int i = 1; i <= n; ++i) {
		scanf("%s", s[i] + 1);
		for(int j = 1; j <= m; ++j) {
			if(s[i][j] == '%') {
				sx = i, sy = j;
			}
		}
	}
	bfs();
	int d1 = inf, d2 = inf;
	for(int i = 1; i <= n; ++i) {
		for(int j = 1; j <= m; ++j) {
			if(s[i][j] == '@') d1 = d[i][j];
			if(s[i][j] == '$' && d[i][j] != -1) {
				d2 = min(d2, d[i][j]);
			}
		}
	}
	if(d1 < d2) puts("Yes");
	else puts("No");
	return 0;
}