Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include<iostream>
#include<queue>
using namespace std;
int dist[205][205];
int x[205][205];bool y[205][205];
int main(){
	int h,w;cin>>h>>w;int gx=0,gy=0,sx=0,sy=0;
	for(int i=1;i<=h;i++){
		for(int j=1;j<=w;j++){
			char B;cin>>B;
			if(B=='%'){gx=i;gy=j;x[i][j]=1;}
			if(B=='$'){x[i][j]=1;y[i][j]=true;}
			if(B=='@'){sx=i;sy=j;x[i][j]=1;}
			if(B=='.'){x[i][j]=1;}
		}
	}
	for(int i=0;i<205*205;i++)dist[i/205][i%205]=114514;
	queue<pair<int,int>>Q;Q.push(make_pair(gx,gy));dist[gx][gy]=0;
	while(!Q.empty()){
		int a1=Q.front().first,a2=Q.front().second;Q.pop();
		int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};
		for(int i=0;i<4;i++){
			int cx=a1+dx[i],cy=a2+dy[i];
			if(x[cx][cy]==0)continue;
			if(dist[cx][cy]>dist[a1][a2]+1){
				dist[cx][cy]=dist[a1][a2]+1;
				Q.push(make_pair(cx,cy));
			}
		}
	}
	int minx=114514;
	for(int i=1;i<=h;i++){
		for(int j=1;j<=w;j++){
			if(y[i][j]==true)minx=min(minx,dist[i][j]);
		}
	}
	if(dist[sx][sy]<minx)cout<<"Yes"<<endl;
	else{cout<<"No"<<endl;}
	return 0;
}