Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
// @Team    : nupt2017team12
// @Author  : Zst
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>
using namespace std;
#define LL long long
#define MOD 1000000007
#define CLR(a,x) memset(a,x,sizeof(a))
#define INF 0x3f3f3f3f
#define pb push_back
#define FOR(i,a,b) for( int i = ( a ); i <= ( b ); ++i )

const int N = 200+7;
char maps[N][N];
int vis[N][N];

int r, c;
int posX, posY;

int princess;
int soldier;

void solve( int x, int y, int times )
{
	vis[x][y] = times;
	if( maps[x][y] == '@' ) {
		princess = min( princess, times );
	} else if( maps[x][y] == '$' ) {
		soldier = min( soldier, times );
	}
	if( x-1 >= 0 ) {
		if( vis[x-1][y] == -1 ) {
			solve( x-1, y, times+1 );
		} else if( times+1 < vis[x-1][y] ) {
			solve( x-1, y, times+1 );
		}
	}
	if( y-1 >= 0 ) {
		if( vis[x][y-1] == -1 ) {
			solve( x, y-1, times+1 );
		} else if( times+1 < vis[x][y-1] ) {
			solve( x, y-1, times+1 );
		}
	}
	if( x+1 < r ) {
		if( vis[x+1][y] == -1 ) {
			solve( x+1, y, times+1 );
		} else if( times+1 < vis[x+1][y] ) {
			solve( x+1, y, times+1 );
		}
	}
	if( y+1 < c ) {
		if( vis[x][y+1] == -1 ) {
			solve( x, y+1, times+1 );
		} else if( times+1 < vis[x][y+1] ) {
			solve( x, y+1, times+1 );
		}
	}
	return;

}


int main()
{
    // freopen( "B.txt", "r", stdin );
    while( scanf( "%d%d", &r, &c ) != EOF ) {
    	princess = soldier = INF;
		CLR( vis, -1 );
	    FOR( i, 0, r-1 ) {
	    	scanf( "%s", maps[i] );
			FOR( j, 0, c-1 ) {
				if( maps[i][j] == '%' ) {
					posX = i;
					posY = j;
				} else if( maps[i][j] == '#' ) {
					vis[i][j] = true;
				}
			}
	    }
	    solve( posX, posY, 0 );
	    if( princess < soldier ) {
	    	printf( "Yes\n");
	    } else {
	    	printf( "No\n");
	    }
	}
	return 0;
}