__author__ = 'Achut'
from collections import deque
class vertex:
def __init__(self,c,a,b):
self.node = c
self.occup = 0
self.count = -1
self.x = a
self.y = b
try:
while True:
m,n = map(int, input().split())
if m == n == 0:
break
a = []
start_x,start_y = 0,0
for i in range(n):
s = input()
x = []
for c in s:
z = vertex(c,i,len(x))
x.append(z)
if c is "S":
start_x,start_y = i,len(x)-1
a.append(x)
queue = deque()
a[start_x][start_y].occup = 1
queue.append(a[start_x][start_y])
ans =[]
while queue:
t = queue.pop()
if t.x - 1 >= 0:# and a[t.x - 1][t.y].occup == 0:
if a[t.x - 1][t.y].node != 'D' and a[t.x - 1][t.y].node != 'X' and a[t.x - 1][t.y].node != 'S':
if a[t.x - 1][t.y].count < 0 or a[t.x - 1][t.y].count > t.count + int(a[t.x - 1][t.y].node):
a[t.x - 1][t.y].count = t.count + int(a[t.x - 1][t.y].node)
#a[t.x-1][t.y].occup = 1
queue.appendleft(a[t.x - 1][t.y])
elif a[t.x - 1][t.y].node == 'D':
ans.append(t.count)
if t.x + 1 < n:# and a[t.x + 1][t.y].occup == 0:
if a[t.x + 1][t.y].node != 'D' and a[t.x + 1][t.y].node != 'X' and a[t.x + 1][t.y].node != 'S':
if a[t.x + 1][t.y].count < 0 or a[t.x + 1][t.y].count > t.count + int(a[t.x + 1][t.y].node):
a[t.x + 1][t.y].count = t.count + int(a[t.x + 1][t.y].node)
#a[t.x+1][t.y].occup = 1
queue.appendleft(a[t.x + 1][t.y])
elif a[t.x + 1][t.y].node == 'D':
ans.append(t.count)
if t.y - 1 >= 0:# and a[t.x][t.y-1].occup == 0:
if a[t.x][t.y - 1].node != 'D' and a[t.x][t.y - 1].node != 'X' and a[t.x][t.y - 1].node != 'S':
if a[t.x][t.y - 1].count < 0 or a[t.x][t.y - 1].count > t.count + int(a[t.x][t.y - 1].node):
a[t.x][t.y-1].count = t.count + int(a[t.x][t.y-1].node)
# a[t.x][t.y-1].occup = 1
queue.appendleft(a[t.x][t.y-1])
elif a[t.x][t.y-1].node == 'D':
ans.append(t.count)
if t.y + 1 < m:# and a[t.x][t.y+1].occup == 0:
if a[t.x][t.y+1].node != 'D' and a[t.x][t.y+1].node != 'X' and a[t.x][t.y+1].node != 'S':
if a[t.x][t.y + 1].count < 0 or a[t.x][t.y + 1].count > t.count + int(a[t.x][t.y + 1].node):
a[t.x][t.y+1].count = t.count + int(a[t.x][t.y+1].node)
#a[t.x][t.y+1].occup = 1
queue.appendleft(a[t.x][t.y+1])
elif a[t.x][t.y+1].node == 'D':
ans.append(t.count)
ans = sorted(ans)
print(ans[0]+1)
except:
pass