Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include "iostream"
#include "climits"
#include "list"
#include "queue"
#include "stack"
#include "set"
#include "functional"
#include "algorithm"
#include "string"
#include "map"
#include "unordered_map"
#include "unordered_set"
#include "iomanip"
#include "cmath"
#include "random"
#include "bitset"
#include "cstdio"
#include "numeric"
#include "cassert"
#include "ctime"

using namespace std;

constexpr long long int MOD = 1000000007;
//constexpr int MOD = 1000000007;
//constexpr int MOD = 998244353;
//constexpr long long int MOD = 998244353;
constexpr double EPS = 1e-12;

//int N, M, K, T, H, W, L, R;
long long int N, M, K, T, H, W, L, R;



int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);

	cin >> H >> W;
	vector<string>s(H);
	for (auto &i : s)cin >> i;
	vector<vector<int>>adis(H, vector<int>(W, MOD));
	vector<vector<int>>bdis(H, vector<int>(W, MOD));
	vector<vector<int>>cdis(H, vector<int>(W, MOD));
	queue<pair<int, int>>Q;
	int dir[] = { 1,0,-1,0,1 };
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			if (s[i][j] == '@') {
				Q.emplace(i, j);
				adis[i][j] = 0;
			}
		}
	}
	while (!Q.empty()) {
		int cy, cx;
		tie(cy, cx) = Q.front();
		Q.pop();
		for (int i = 0; i < 4; i++) {
			int ny = cy + dir[i];
			int nx = cx + dir[i + 1];
			if (ny < 0 || nx < 0 || ny >= H || nx >= W)continue;
			if (s[ny][nx] == '#')continue;
			if (adis[ny][nx] > adis[cy][cx] + 1) {
				adis[ny][nx] = adis[cy][cx] + 1;
				Q.emplace(ny, nx);
			}
		}
	}
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			if (s[i][j] == '$') {
				Q.emplace(i, j);
				bdis[i][j] = 0;
			}
		}
	}
	while (!Q.empty()) {
		int cy, cx;
		tie(cy, cx) = Q.front();
		Q.pop();
		for (int i = 0; i < 4; i++) {
			int ny = cy + dir[i];
			int nx = cx + dir[i + 1];
			if (ny < 0 || nx < 0 || ny >= H || nx >= W)continue;
			if (s[ny][nx] == '#')continue;
			if (bdis[ny][nx] > bdis[cy][cx] + 1) {
				bdis[ny][nx] = bdis[cy][cx] + 1;
				Q.emplace(ny, nx);
			}
		}
	}
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			if (s[i][j] == '@') {
				Q.emplace(i, j);
				cdis[i][j] = 0;
			}
		}
	}
	while (!Q.empty()) {
		int cy, cx;
		tie(cy, cx) = Q.front();
		Q.pop();
		for (int i = 0; i < 4; i++) {
			int ny = cy + dir[i];
			int nx = cx + dir[i + 1];
			if (ny < 0 || nx < 0 || ny >= H || nx >= W)continue;
			if (s[ny][nx] == '#')continue;
			if (adis[ny][nx] >= bdis[ny][nx])continue;
			if (cdis[ny][nx] > cdis[cy][cx] + 1) {
				cdis[ny][nx] = cdis[cy][cx] + 1;
				Q.emplace(ny, nx);
			}
		}
	}
	int ans = MOD;
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			if (s[i][j] == '%') {
				ans = cdis[i][j];
			}
		}
	}
	if (ans == MOD)cout << "No\n";
	else cout << "Yes\n";
}