Problem: Example

Input

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


Output

Yes

Solution (in CPP):

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

using namespace std;
typedef long long ll;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<ll> VL;
typedef vector<VL> VVL;
typedef pair<int, int> PII;

#define FOR(i, a, n) for (ll i = (ll)a; i < (ll)n; ++i)
#define REP(i, n) FOR(i, 0, n)
#define ALL(x) x.begin(), x.end()
#define MP make_pair
#define PB push_back
#define MOD 1000000007
#define INF (1LL<<30)
#define LLINF (1LL<<60)
#define PI 3.14159265359
#define EPS 1e-12
//#define int ll

string maze[210];
int d[210][210], dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1}, h, w, gx, gy;
int bfs(int sx, int sy) {
	queue<PII> que;
	REP(i, h) REP(j, w) d[i][j] = INF;
	que.push(PII(sx, sy));
	d[sy][sx] = 0;
	while(que.size()) {
		PII p = que.front(); que.pop();
		//cout << p.first << " " << p.second << endl;
		//if(p.first == gx && p.second == gy) break;
		REP(i, 4) {
			int nx = p.first + dx[i], ny = p.second + dy[i];
			if(0 <= nx && nx < w && 0 <= ny && ny < h && maze[ny][nx] != '#' && d[ny][nx] == INF) {
				que.push(PII(nx, ny));
				d[ny][nx] = d[p.second][p.first] + 1;
			}
		}
	}
	/*REP(i, h) {
		REP(j, w) {
			cout << d[i][j] << " ";
		}
		cout << endl;
	}*/
	return d[gy][gx];
}

signed main(void)
{
	cin >> h >> w;
	REP(i, h) cin >> maze[i];

	int py, px;
	VI sy, sx;
	REP(i, h) REP(j, w) {
		if(maze[i][j] == '@') {py = i; px = j;}
		else if(maze[i][j] == '$') {sy.PB(i); sx.PB(j);}
		else if(maze[i][j] == '%') {gy = i; gx = j;}
	}

	bfs(gx, gy);

	int p = d[py][px];
	int s = INF;
	REP(i, sx.size()) s = min(s, d[sy[i]][sx[i]]);

	//cout << p << " " << s << endl;
	/*REP(i, h) {
		REP(j, w) {
			cout << d[i][j] << " ";
		}
		cout << endl;
	}*/
	if(s <= p) cout << "No" << endl;
	else cout << "Yes" << endl;

	return 0;
}