Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <bits/stdc++.h>
using namespace std;
#define FOR(i,k,n) for(int i = (int)(k); i < (int)(n); i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(a) a.begin(), a.end()
#define MS(m,v) memset(m,v,sizeof(m))
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<string> vs;
typedef pair<int, int> pii;
const int MOD = 1000000007;
const int INF = MOD + 1;
const ld EPS = 1e-12;
template<class T> T &chmin(T &a, const T &b) { return a = min(a, b); }
template<class T> T &chmax(T &a, const T &b) { return a = max(a, b); }

/*--------------------template--------------------*/

const int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };
//const int dx[] = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy[] = { 0, -1, 1, -1, 1, 0, -1, 1 };
bool valid(int x, int y, int h, int w) { return (x >= 0 && y >= 0 && x < h&&y < w); }
int place(int x, int y, int w) { return w*x + y; }


int main()
{
	cin.sync_with_stdio(false); cout << fixed << setprecision(10);
	int h, w;
	cin >> h >> w;
	vs fld(h);
	REP(i, h) cin >> fld[i];
	int sx, sy;
	REP(i, h)REP(j, w)
	{
		if (fld[i][j] == '%')
		{
			sx = i; sy = j;
		}
	}
	int pr = INF, so = INF;
	queue<pii> que;
	que.emplace(sx, sy);
	vector<vi> dist(h, vi(w, INF));
	dist[sx][sy] = 0;
	while (!que.empty())
	{
		int x = que.front().first;
		int y = que.front().second;
		que.pop();
		if (fld[x][y] == '@') chmin(pr, dist[x][y]);
		if (fld[x][y] == '$') chmin(so, dist[x][y]);
		REP(i, 4)
		{
			int nx = x + dx[i];
			int ny = y + dy[i];
			if (!valid(nx, ny, h, w) || fld[nx][ny] == '#' || dist[nx][ny] < INF) continue;
			dist[nx][ny] = dist[x][y] + 1;
			que.emplace(nx, ny);
		}
	}
	cout << (pr < so ? "Yes" : "No") << endl;
	return 0;
}