Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
#define rep(i,n)for(int i=0;i<n;i++)
using namespace std;
typedef pair<int, int>P;

char s[200][201];
int d1[200][200], d2[200][200];
bool b[200][200];
int dx[]{ 1,-1,0,0 }, dy[]{ 0,0,1,-1 };
int h, w;

void dfs(int x, int y) {
	b[x][y] = true;
	rep(i, 4) {
		int nx = x + dx[i], ny = y + dy[i];
		if (0 <= nx&&nx < h && 0 <= ny&&ny < w && !b[nx][ny] && d2[nx][ny] < d1[nx][ny])
			dfs(nx, ny);
	}
}
int main() { 
	scanf("%d%d", &h, &w);
	memset(d1, 0x3f, sizeof(d1));
	memset(d2, 0x3f, sizeof(d2));
	queue<P>que;
	int sx, sy, gx, gy;
	rep(i, h) {
		scanf("%s", s[i]);
		rep(j, w) {
			if (s[i][j] == '$') {
				d1[i][j] = 0; que.push(P(i, j));
			}
			if (s[i][j] == '@')sx = i, sy = j;
			if (s[i][j] == '%')gx = i, gy = j;
		}
	}
	while (!que.empty()) {
		P p = que.front(); que.pop();
		rep(i, 4) {
			int nx = p.first + dx[i], ny = p.second + dy[i];
			if (0 <= nx&&nx < h && 0 <= ny&&ny < w&&s[nx][ny] != '#'&&d1[nx][ny] == INF) {
				d1[nx][ny] = d1[p.first][p.second] + 1;
				que.push(P(nx, ny));
			}
		}
	}
	que.push(P(sx, sy));
	d2[sx][sy] = 0;
	while (!que.empty()) {
		P p = que.front(); que.pop();
		rep(i, 4) {
			int nx = p.first + dx[i], ny = p.second + dy[i];
			if (0 <= nx&&nx < h && 0 <= ny&&ny < w&&s[nx][ny] != '#'&&d2[nx][ny] == INF) {
				d2[nx][ny] = d2[p.first][p.second] + 1;
				que.push(P(nx, ny));
			}
		}
	}
	dfs(sx, sy);
	puts(b[gx][gy] ? "Yes" : "No");
}