Problem: Example

Input

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


Output

Yes

Solution (in CPP):

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

using namespace std;

typedef pair <int, int> cell;

#define x first
#define y second
#define mp make_pair

const int N = 205;

int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};

char g[N][N];
int h, w, sx, sy, d[N][N];
int princess;
vector <int> soldiers;

bool valid (int x, int y) {
	return x >= 1 and y >= 1 and x <= h and y <= w and g[x][y] != '#';
}

void bfs (void) {
	queue <cell> q;
	q.push(mp(sx, sy));
	memset(d, -1, sizeof d);
	d[sx][sy] = 0;

	while (not q.empty()) {
		cell u = q.front(); q.pop();
		for (int k = 0; k < 4; ++k) {
			int nx = u.x + dx[k], ny = u.y + dy[k];
			if (!valid(nx, ny)) continue;
			if (d[nx][ny] != -1) continue;

			d[nx][ny] = d[u.x][u.y] + 1;
			q.push(mp(nx, ny));

			if (g[nx][ny] == '@') princess = d[nx][ny];
			else if (g[nx][ny] == '$') soldiers.push_back(d[nx][ny]);
		}
	}
}

int main (int argc, char const *argv[]) {
	scanf("%d %d", &h, &w);
	for (int i = 1; i <= h; ++i) {
		scanf("%s", g[i] + 1);
		for (int j = 1; j <= w; ++j) {
			if (g[i][j] == '%') sx = i, sy = j;  
		}
	}

	bfs();

	int flag = 1;
	for (int i = 0; i < (int) soldiers.size(); ++i) {
		if (soldiers[i] <= princess) {
			flag = 0;
			break;
		}
	}

	puts(flag ? "Yes" : "No");
    return 0;
}