#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
int dx[4] = {0, 0, -1, 1};
int dy[4] = {-1, 1, 0, 0};
int a[1000][1000];
bool visited[1000][1000] = {0};
int sum = 0;
cin >> n >> m;
int x = 0, y = 0, min_val = 1e6;
for (int i = 0; i < n; i++) { // y
for (int j = 0; j < m; j++) { // x
cin >> a[i][j];
if (a[i][j] < min_val) {
min_val = a[i][j];
x = j;
y = i;
}
}
}
int nx = -1, ny = -1, nv = 0;
while (1) {
sum += a[y][x];
visited[y][x] = 1;
int nextx = -1, nexty = -1, nv = 1e6;
for (int d = 0; d < 4; d++) {
int nx = x + dx[d];
int ny = y + dy[d];
if (nx >= 0 && nx < m && ny >= 0 && ny < n && !visited[ny][nx]) {
if (a[ny][nx] < nv) {
nv = a[ny][nx];
nextx = nx;
nexty = ny;
}
}
}
if (nextx == -1) break;
x = nextx;
y = nexty;
}
cout << sum;
}