Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define pii pair<int, int>
#define ff first
#define ss second

typedef vector<int> vi;
int ara[205][205];
pii d, p;

vector<string> grid;
int xx[] = {0, 0, 1, -1};
int yy[] = {1, -1, 0, 0};
int n, m;

bool isValid(int x, int y){
	return (x>=0 && y>=0 && x<n && y<m);	
}

void cost(int x, int y){
	queue<int> qx, qy;
	qx.push(x);
	qy.push(y);
	memset(ara, 0, sizeof(ara));
	ara[x][y] = 1;
	while(!qx.empty()){
		x = qx.front();
		y = qy.front();
		qx.pop();
		qy.pop();
		for(int i=0; i<4; i++){
			int tx = x+xx[i], ty = y+yy[i];
			if(isValid(tx, ty) && !ara[tx][ty] && grid[tx][ty] != '#'){
				qx.push(tx);
				qy.push(ty);
				ara[tx][ty] = ara[x][y]+1;
			}

		}
	}
}

int main(){
	scanf("%d %d",&n, &m);

    grid = vector<string>(n);
	for(int i=0; i<n; i++){
		cin >> grid[i];
	}
	
	for(int i=0; i<n; i++){
		for(int j=0; j<m; j++){
			if(grid[i][j] == '%') d = mp(i, j);
			else if(grid[i][j] == '@') p = mp(i, j);		
		}
	}

	cost(d.ff, d.ss);
	
	bool flag = true;
	int mn = ara[p.ff][p.ss], t;
	for(int i=0; i<n && flag; i++){
		for(int j=0; j<m && flag; j++){
			if(grid[i][j] == '$'){
				flag = (mn < ara[i][j]);
			}	
		}
	}
	
	if(flag) printf("Yes\n");
	else printf("No\n");
	return 0;
}