#include <algorithm>
#include <iostream>
#include <vector>
#include <cstring>
#include <queue>

using namespace std;

#define MAXN 1005
#define x first
#define y second

int dx[] = { 1, 1, 0, -1, -1, -1, 0, 1 };
int dy[] = { 0, 1, 1, 1, 0, -1, -1, -1 };

int n, m;
int dist[MAXN][MAXN];
bool was[MAXN][MAXN];
char S[MAXN][MAXN];

pair < int, int > chef, kapa, u, p;

bool test( int udalj ){
     
     if( dist[chef.x][chef.y] < udalj )
       return false;
     
     queue < pair <int, int> > Q;
     Q.push( chef ); 
     
     memset( was, 0, sizeof(was) );
     was[chef.x][chef.y] = true;

     while( !Q.empty() ){
            u = Q.front(); Q.pop();
            
            if( u == kapa )return true;
            
            for(int i = 0; i < 8; ++i){
               p = make_pair(dx[i] + u.x, dy[i] + u.y);
               if( p.x < 0 || p.x >= n || p.y < 0 || p.y >= m)continue; 
               if( !was[p.x][p.y] && dist[p.x][p.y] >= udalj ){
                    was[p.x][p.y] = true;
                    Q.push( p );
               }
            }
     }
     
    return false;
} 

int main(){

    scanf("%d %d", &n, &m );
    
    queue < pair<int, int> > Q;
    memset(dist, -1, sizeof(dist));
    
    for(int i = 0; i < n; ++i){
       scanf("%s", S[i] );
       for(int j = 0; j < m; ++j){
           if( S[i][j] == '@' )chef = make_pair(i, j);
           if( S[i][j] == '$' )kapa = make_pair(i, j);
           if( S[i][j] == 'D' ){ Q.push( make_pair( i,j ) ); dist[i][j] = 0; } 
       }
    }
    
    while( !Q.empty()){
           u = Q.front(); Q.pop();
           for(int i = 0; i < 8; ++i){
               p = make_pair(dx[i] + u.x, dy[i] + u.y);
               if( p.x < 0 || p.x >= n || p.y < 0 || p.y >= m)continue; 
               if( dist[p.x][p.y] == -1 ){
                   dist[p.x][p.y] = dist[u.x][u.y] + 1;
                   Q.push( p );
               }
           }
    }
    
    int lo = 0, hi = n * m, mid;
    while( hi - lo > 1 ){
           mid = (lo + hi) / 2;
           if( test(mid) )lo = mid; else hi = mid;
    }
    
    printf("%d\n", lo );
    return 0;
}