Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include<cstdio>
#include<queue>
#define N 205
using namespace std;
queue<int> Q;
const int dx[5]={1,-1,0,0},dy[5]={0,0,1,-1};
int h,w,a[N][N],vis[N][N],x,y,ans,flag,cnt;
char ch;
struct he{
	int x,y,s;
}q[N*N];
int main(){
	scanf("%d%d",&h,&w);
	for(int i=1;i<=h;i++){
		for(int j=1;j<=w;j++){
			ch=getchar();
			while(!(ch=='.'||ch=='@'||ch=='%'||ch=='#'||ch=='$')) ch=getchar();
			if(ch=='.') a[i][j]=1;
			if(ch=='@') a[i][j]=2;
			if(ch=='%') a[i][j]=3,x=i,y=j;
			if(ch=='#') a[i][j]=4;
			if(ch=='$') a[i][j]=5;
		}
	}
	q[1].x=x;q[1].y=y;cnt=1;
	vis[x][y]=1;
	Q.push(1);
	while(!Q.empty()){
		int u=Q.front();Q.pop();
		int x0=q[u].x,y0=q[u].y;
		if(flag==1&&ans<=q[u].s) break;
		for(int i=0;i<4;i++){
			int x1=x0+dx[i];
			int y1=y0+dy[i];
			if(x1<1||x1>h||y1<1||y1>w) continue;
			if(a[x1][y1]==4||vis[x1][y1]) continue;
			if(a[x1][y1]==5){flag=-1;break;}
			if(a[x1][y1]==2) {flag=1;ans=q[u].s+1;}
			q[++cnt].x=x1;q[cnt].y=y1;
			vis[x1][y1]=1;
			q[cnt].s=q[u].s+1;
			Q.push(cnt);
		}
		if(flag==-1) break;
	}
	if(flag==1) printf("Yes\n");else printf("No\n");
}