#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#define MAXX 2000
#define MAXA 4800000

int visited[MAXX][MAXX];
int A[MAXX][MAXX];
int H, W, len;

bool better(int a, int b) {
    return abs(a) < abs(b) or (abs(a) == abs(b) and a < 0);
}

int hike(int r, int c, char dir) {
    if (visited[r][c] > 0) return len + visited[r][c] - 1;
    visited[r][c] = ++len;
    int best = MAXA, rb = -1, cb = -1;
    char db = 'X';
    if (r > 0 and dir != 'E' and better(A[r-1][c]-A[r][c], best)) {
        db = 'W';
        rb = r-1;
        cb = c;
        best = A[rb][cb] - A[r][c];
    }
    if (r < H-1 and dir != 'W' and better(A[r+1][c]-A[r][c], best)) {
        db = 'E';
        rb = r+1;
        cb = c;
        best = A[rb][cb] - A[r][c];
    }
    if (c > 0 and dir != 'S' and better(A[r][c-1]-A[r][c], best)) {
        db = 'N';
        rb = r;
        cb = c-1;
        best = A[rb][cb] - A[r][c];
    }
    if (c < W-1 and dir != 'N' and better(A[r][c+1]-A[r][c], best)) {
        db = 'S';
        rb = r;
        cb = c+1;
        best = A[rb][cb] - A[r][c];
    }
    return hike(rb, cb, db);
}

int main() {
    FILE *fr, *fw;
    int i, j;

#ifdef EVAL
    fr = fopen("input.txt", "r");
    fw = fopen("output.txt", "w");
#else
    fr = stdin;
    fw = stdout;
#endif
    assert(2 == fscanf(fr, "%d %d", &H, &W));
    for(i=0; i<H; i++)
        for(j=0; j<W; j++)
            assert(1 == fscanf(fr, "%d", &A[i][j]));

    fprintf(fw, "%d\n", hike(0, 0, 'X'));
    fclose(fr);
    fclose(fw);
    return 0;
}
