h, w = map(int, input().split()) S = [list(input()) for _ in range(h)] Directions = [(1, 0), (0, 1)] ans = S[0][0] C = [0] for _ in range(h + w - 2): minT = '' NC = [] for c in C: ci, cj = divmod(c, w) for di, dj in Directions: ni = ci + di nj = cj + dj if ni < h and nj < w: if minT == '': minT = S[ni][nj] NC.append(ni * w + nj) elif S[ni][nj] == minT: NC.append(ni * w + nj) elif S[ni][nj] < minT: minT = S[ni][nj] NC = [ni * w + nj] ans += minT C = NC print(ans)