Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <stdio.h>
#include <cmath>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
typedef long long int ll;

using namespace std;

struct Info{
	Info(int arg_row,int arg_col,int arg_dist){
		row = arg_row;
		col = arg_col;
		dist = arg_dist;
	}
	Info(){
		row = 0,col = 0,dist = 0;
	}

	int row,col,dist;
};

int H,W,div_row[4] = {-1,0,0,1},div_col[4] = {0,-1,1,0};

bool rangeCheck(int row,int col){
	if(row >= 0 && row <= H-1 && col >= 0 && col <= W-1)return true;
	else{
		return false;
	}
}

int main(){

	int escape_row,escape_col;
	scanf("%d %d",&H,&W);
	char map[200][201];

	int distance[200][200];

	for(int i = 0; i < H; i++){
		scanf("%s",map[i]);
		for(int k = 0; k < W;k++){
			distance[i][k] = -1;
			if(map[i][k] == '%'){
				escape_row = i;
				escape_col = k;
			}
		}
	}

	distance[escape_row][escape_col] = 0;

	int prin = -1,enemy = 50000;

	queue<Info> Q;

	Q.push(Info(escape_row,escape_col,0));
	Info current;

	while(!Q.empty()){
		current = Q.front();
		Q.pop();

		if(map[current.row][current.col] == '@'){
			if(prin == -1){
				prin = current.dist;
			}else{
				prin = min(prin,current.dist);
			}
			continue;
		}else if(map[current.row][current.col] == '$'){
			enemy = min(enemy,current.dist);
			continue;
		}

		if((prin != -1 && current.dist >= prin) || (current.dist >= enemy))continue;

		for(int i = 0; i < 4; i++){
			if(rangeCheck(current.row+div_row[i],current.col+div_col[i]) == true && map[current.row+div_row[i]][current.col+div_col[i]] != '#' &&
					(distance[current.row+div_row[i]][current.col+div_col[i]] == -1 || distance[current.row+div_row[i]][current.col+div_col[i]] > current.dist+1)){
				distance[current.row+div_row[i]][current.col+div_col[i]] = current.dist+1;
				Q.push(Info(current.row+div_row[i],current.col+div_col[i],current.dist+1));
			}
		}
	}

	if(prin == -1 || prin >= enemy){
		printf("No\n");
	}else{
		printf("Yes\n");
	}

    return 0;
}