Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include<iostream>
#include<stdio.h>
#include<cstring>
#include<math.h>
#include<queue>
using namespace std;
char map[210][210];
int step[210][210];
int px,py,ex,ey;
int pstep=500,sstep=500;
struct node
{
	int x,y,step;
}a[410];
void bfs(int h,int w)
{
	queue<node>Q;
	while(!Q.empty()) Q.pop();
	node tem;
	tem.x=ex,tem.y=ey;
	tem.step=0;
	step[tem.x][tem.y]=0;
	Q.push(tem);
	while(!Q.empty())
	{
		tem=Q.front();
		Q.pop();
		if(map[tem.x][tem.y]=='@' && tem.step<pstep)
			pstep=tem.step;
		else if(map[tem.x][tem.y]=='$' && tem.step<sstep)
			sstep=tem.step;
		node t;
		if(tem.x-1>=0 && map[tem.x-1][tem.y]!='#' && tem.step+1<step[tem.x-1][tem.y])
		{
			t.x=tem.x-1;
			t.y=tem.y;
			t.step=tem.step+1;
			step[t.x][t.y]=t.step;
		/*	if(map[tem.x-1][tem.y]=='@' && t.step<pstep)
				pstep=t.step;
			else if(map[tem.x-1][tem.y]=='$' && t.step<sstep)
				sstep=t.step;
				*/
			Q.push(t);
		}
		if(tem.x+1<h && map[tem.x+1][tem.y]!='#' && tem.step+1<step[tem.x+1][tem.y] )
		{
			t.x=tem.x+1;
			t.y=tem.y;
			t.step=tem.step+1;
			step[t.x][t.y]=t.step;
			/*
		   if(map[tem.x+1][tem.y]=='@' && t.step<pstep)
				pstep=t.step;
			else if(map[tem.x+1][tem.y]=='$' && t.step<sstep)
				sstep=t.step;
				*/
			Q.push(t);
		}
		if(tem.y-1>=0 && map[tem.x][tem.y-1]!='#' && tem.step+1<step[tem.x][tem.y-1])
		{
			t.x=tem.x;
			t.y=tem.y-1;
			t.step=tem.step+1;
			step[t.x][t.y]=t.step;
			/*
		   if(map[tem.x][tem.y-1]=='@' && t.step<pstep)
				pstep=t.step;
			else if(map[tem.x][tem.y-1]=='$' && t.step<sstep)
				sstep=t.step;
				*/
			Q.push(t);
		}
		if(tem.y+1<w && map[tem.x][tem.y+1]!='#' && tem.step+1<step[tem.x][tem.y+1])
		{
			t.x=tem.x;
			t.y=tem.y+1;
			t.step=tem.step+1;
			step[t.x][t.y]=t.step;
			/*
			if(map[tem.x][tem.y+1]=='@' && t.step<sstep)
				sstep=t.step;
			else if(map[tem.x][tem.y+1]=='$' && t.step<sstep)
				sstep=t.step;
				*/
			Q.push(t);
		}
	}
}

int main()
{
	int h,w;
	while(scanf("%d%d",&h,&w)!=EOF)
	{
		pstep=500,sstep=500;
		memset(a,0,sizeof(a));
		memset(step,0x3f,sizeof(step));
		int i,j;
		for(i=0;i<h;i++)
		{
			scanf("%s",&map[i]);
			for(j=0;j<w;j++)
			{
				if(map[i][j]=='@')
				{
					px=i;py=j;
				}
				else if(map[i][j]=='%')
					ex=i,ey=j;
			}
		}
		bfs(h,w);
		if(pstep<sstep)
			printf("Yes\n");
		else
			printf("No\n");
	}
	return 0;
}