Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <bits/stdc++.h>
using namespace std;

struct P {
	int x, y;
	P() : x(0), y(0) {}
	P(int x, int y)
		: x(x), y(y) {}
};

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

int main()
{
	int H, W;
	P s, g;
	vector<P> q, sol;
	char c;
	cin >> H >> W;
	vector<vector<int>> a(H, vector<int>(W, 1));
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			cin >> c;
			if (c == '%') {
				g.x = i, g.y = j;
			}
			else if (c == '@') {
				s.x = i, s.y = j;
				a[i][j] = 0;
				q.push_back(s);
			}
			else if (c == '$') {
				sol.push_back(P(i, j));
				a[i][j] = -1;
			}
			else if (c == '#') {
				a[i][j] = -1;
			}
		}
	}
	bool res = false;
	while (!q.empty()) {
		vector<P> tq, tsol;
		for (auto p : sol) {
			for (int i = 0; i < 4; i++) {
				int tx = p.x + dx[i], ty = p.y + dy[i];
				if (tx >= 0 && tx < H && ty >= 0 && ty < W && a[tx][ty] != -1) {
					a[tx][ty] = -1;
					tsol.push_back(P(tx, ty));
				}
			}
		}
		for (auto p : q) {
			for (int i = 0; i < 4; i++) {
				int tx = p.x + dx[i], ty = p.y + dy[i];
				if (tx >= 0 && tx < H && ty >= 0 && ty < W && a[tx][ty] == 1) {
					if (tx == g.x && ty == g.y) {
						res = true;
						tq.clear();
						break;
					}
					a[tx][ty] = 0;
					tq.push_back(P(tx, ty));
				}
			}
		}
		q = tq, sol = tsol;
	}
	cout << (res ? "Yes" : "No") << endl;
	return 0;
}