Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <algorithm>
using namespace std;
 
#define REP(i,n) for(int i=0; i<n; ++i)
#define FOR(i,a,b) for(int i=a; i<=b; ++i)
#define FORR(i,a,b) for (int i=a; i>=b; --i)
#define pi acos(-1.0)
 
typedef long long ll;
typedef vector<int> VI;
typedef vector<ll> VL;
typedef vector<VI> VVI;
typedef pair<int,int> P;
typedef pair<ll,ll> PL;

int main(){
	int h, w;
	cin >> h >> w;
	vector<string> m(h);
	REP(i,h) cin >> m[i];
	int sx, sy;
	REP(i,h) REP(j,w) if(m[i][j] == '%') {sx = i, sy = j;}

	VVI d(h,VI(w));
	d[sx][sy] = 1;
	queue<P> que;
	que.push(make_pair(sx, sy));
	while (!que.empty()){
		P p = que.front();
		que.pop();
		int i = p.first, j = p.second;
		int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1};
		REP(k,4){
			int ii = i + dx[k], jj = j + dy[k];
			if (ii < 0 || jj < 0 || ii >= h || jj >= w) continue;
			if (m[ii][jj] == '#' || d[ii][jj] > 0) continue;
			d[ii][jj] = d[i][j] + 1;
			que.push(make_pair(ii, jj));
		}
	}
	int p, s;
	s = 1e9;
	REP(i,h) REP(j,w){
		if (m[i][j] == '@') p = d[i][j];
		if (m[i][j] == '$') s = min(s, d[i][j]);
	}
	cout << (p < s ? "Yes" : "No") << endl;
    return 0;
}