#include <bits/stdc++.h>
using namespace std; 
const int inf = 1e9 + 7;
int n, m;
int dx[] = {1, -1, 0, 0, 1, -1, 1, -1};
int dy[] = {0, 0, 1, -1, 1, -1, -1, 1};
struct node {
    int dif, x, y;
    bool operator<(const node &other) const {
        return dif > other.dif;
    }
};
bool ok(int x, int y) {
    return  x >= 1 && x <= n && y >= 1 && y <= m;
}
vector<vector<int>> dijkstra(int x, int y, vector<vector<char>> a) {
    vector<vector<int>> dist(n + 5, vector<int> (m + 5, inf));
    dist[x][y] = (a[x][y] == '#' ? 0 : (a[x][y] - '0'));
    priority_queue<node> q;
    q.push({dist[x][y], x, y});
    while (q.size()) {
        int x = q.top().x;
        int y = q.top().y;
        int dif = q.top().dif;
        q.pop();
        if (dif > dist[x][y]) continue;
        for (int d = 0; d < 8; d++) {
            int nx = x + dx[d];
            int ny = y + dy[d];
            if (!ok(nx, ny)) continue;
            if (a[nx][ny] == '.') continue;
            int add = a[nx][ny] == '#' ? 0 : (a[nx][ny] - '0');
            if (dist[nx][ny] > dist[x][y] + add) {
                dist[nx][ny] = dist[x][y] + add;
                q.push({dist[nx][ny], nx, ny}); 
            }
        }
    }
    return dist;
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin >> n >> m;
    vector<vector<char>> a(n + 5, vector<char> (m + 5, 0));
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            cin >> a[i][j]; 
        }
    } 
    int ans = inf; 
    for (int i = 1; i <= m; i++) {
        if (a[1][i] == '.') continue;
        vector<vector<int>> dist = dijkstra(1, i, a);
        for (int j = 2; j <= n; j++) ans = min(ans, dist[j][1]);
        for (int j = 1; j <= m; j++) ans = min(ans, dist[n][j]);
    }
    for (int j = 1; j <= m; j++) {
        if (a[n][j] == '.') continue;
        vector<vector<int>> dist = dijkstra(n, j, a);
        for (int i = 1; i <= n; ++i) ans = min(ans, dist[i][m]);
    }
    for (int i = 1; i <= n; i++) {
        if (a[i][1] == '.') continue;
        vector<vector<int>> dist = dijkstra(i, 1, a);
        for (int j = 1; j <= n; j++) ans = min(ans, dist[j][m]);
    }
    cout << ans << '\n'; 
    return 0;
}

/*
break
could
misty
phone
deads
*/ 