Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
int dx[4]={1, 0, 0,-1};
int dy[4]={0, 1,-1, 0};

struct info{
	int y;
	int x;
	int dist;
	info(int y, int x, int d): y(y),x(x),dist(d){}
};

int main(){
	int h,w;
	cin >> h >> w;
	vector<vector<char> > map(h+2, vector<char>(w+2, '#'));
	int sy, sx;
	for(int i=1; i<=h; i++){
		for(int j=1; j<=w; j++){
			cin >> map[i][j];
			if(map[i][j]=='%'){
				sy = i;
				sx = j;
			}
		}
	}
	
	queue<info> q;
	q.push(info(sy, sx, 0));
	map[sy][sx] = '#';
	int princess=-1, soldier=-1;
	while(!q.empty()){
		int y=q.front().y;
		int x=q.front().x;
		int d=q.front().dist;
		q.pop();
		for(int i=0; i<4; i++){
			int ny=y+dy[i], nx=x+dx[i];
			if(map[ny][nx] != '#'){
				if(map[ny][nx]=='@'){
					princess=d;
				}
				if(map[ny][nx]=='$' && soldier==-1){
					soldier=d;
				}
				q.push(info(ny, nx, d+1));
				map[ny][nx] = '#';
			}
		}
	}
	
	if(soldier==-1 || princess < soldier){
		cout << "Yes" << endl;
	}else{
		cout << "No" << endl;
	}
	return 0;
}