Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include<iostream>
#include<queue>
using namespace std;
struct node{
	int r,c,cen;
};
int h,w;
int p=-1;
int s=-1;
char map[250][250];
//int cen[250][250]={0};
int vis[250][250]={0};
int d[2][4]={1,-1,0,0,0,0,1,-1};
int ok(int r,int c){
	if(r<0||r>=h) return false;
	if(c<0||c>=w) return false;
	if(map[r][c]=='#') return false;
	if(vis[r][c]) return false;
	return true;
}
void bfs(int r,int c){
	vis[r][c] = 1;
	node st;st.r=r;st.c=c;st.cen=0;
	queue<node> q;q.push(st);
	while(!q.empty()){
		node t = q.front();
		q.pop();
		if(map[t.r][t.c]=='$'){
			if(s==-1) s = t.cen;
			else s = min(s,t.cen);
		}
		else if(map[t.r][t.c]=='@'){
			if(p==-1) p = t.cen;
			else p = min(p,t.cen);
		}
		for(int i=0;i<4;++i){
			if(ok(t.r+d[0][i],t.c+d[1][i])){
				vis[t.r+d[0][i]][t.c+d[1][i]] = 1;
				q.push((node){t.r+d[0][i],t.c+d[1][i],t.cen+1});
			}
		}
	}
}
int main(){
	int i,j;
	cin>>h>>w;
	for(i=0;i<h;++i){
		scanf("%s",map[i]);
	}
	for(i=0;i<h;++i){
		for(j=0;j<w;++j){
			if(map[i][j]=='%') {
				 bfs(i,j);
			}
		}
	}
	if(p==-1){
		printf("No\n");
	}
	else if(s==-1){
		printf("Yes\n");
	}
	else if(p>=s) printf("No\n");
	else printf("Yes\n");
}