Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include "bits/stdc++.h"
using namespace std;

//#define int long long
#define DBG 1
#define dump(o) if(DBG){cerr<<#o<<" "<<(o)<<" ";}
#define dumpl(o) if(DBG){cerr<<#o<<" "<<(o)<<endl;}
#define dumpc(o) if(DBG){cerr<<#o; for(auto &e:(o))cerr<<" "<<e;cerr<<endl;}
#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--)
#define all(c) begin(c),end(c)
const int INF = sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f;
const int MOD = (int)(1e9 + 7);
template<class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; }
template<class T> bool chmin(T &a, const T &b) { if (a > b) { a = b; return true; } return false; }
#define MAX 210
char c[MAX][MAX];
int p[MAX][MAX], s[MAX][MAX];
int H, W;
bool inrange(int i, int j) {
	return 0 <= i&&i < H && 0 <= j&&j < W;
}
int di[] = { 1,0,-1,0 };
int dj[] = { 0,1,0,-1 };
int bfsp(int si, int sj) {
	queue<pair<int, int>> Q, NQ;
	NQ.emplace(si, sj);
	int cnt = 0;
	while (NQ.size()) {
		swap(Q, NQ);
		while (Q.size()) {
			auto a = Q.front(); Q.pop();
			int i = a.first, j = a.second;
			if (!inrange(i, j))continue;
			if (c[i][j] == '#')continue;
			if (p[i][j] <= cnt)continue;
			p[i][j] = cnt;
			if (c[i][j] == '%')return cnt;
			rep(h, 0, 4) {
				NQ.emplace(i + di[h], j + dj[h]);
			}
		}
		cnt++;
	}
	return INF;
}
int bfss(int si, int sj) {
	queue<pair<int, int>> Q, NQ;
	NQ.emplace(si, sj);
	int cnt = 0;
	while (NQ.size()) {
		swap(Q, NQ);
		while (Q.size()) {
			auto a = Q.front(); Q.pop();
			int i = a.first, j = a.second;
			if (!inrange(i, j))continue;
			if (c[i][j] == '#')continue;
			if (s[i][j] <= cnt)continue;
			s[i][j] = cnt;
			if (c[i][j] == '$')return cnt;
			rep(h, 0, 4) {
				NQ.emplace(i + di[h], j + dj[h]);
			}
		}
		cnt++;
	}
	return INF;
}

signed main() {
	cin >> H >> W;
	int si = -1, sj;
	memset(p, 0x3f, sizeof(p));
	memset(s, 0x3f, sizeof(s));
	rep(i, 0, H)rep(j, 0, W) {
		cin >> c[i][j];
	}
	int a = INF;
	rep(i, 0, H)rep(j, 0, W) {
		if (c[i][j] == '@')a = bfsp(i, j);
	}
	int b = INF;
	rep(i, 0, H)rep(j, 0, W) {
		if (c[i][j] == '%')chmin(b, bfss(i, j));
	}

	if (a >= b)cout << "No" << endl;
	else cout << "Yes" << endl;
	return 0;
}