from collections import namedtuple
from queue import PriorityQueue

NORTH, SOUTH, WEST, EAST = (0, -1), (0, 1), (-1, 0), (1, 0)

Cell = namedtuple('Cell', 'level x y')

def max_water_heldover_minheap(heights, display=None):
    """from http://w...content-available-to-author-only...u.com/p/540ee7ec725b"""
    q = PriorityQueue()
    nrows = len(heights)
    ncolumns = len(heights[0])
    seen = [[False] * ncolumns for _ in range(nrows)]

    # enqueue cells on the perimeter of the island
    for y in range(nrows):
        seen[y][0] = True
        q.put(Cell(heights[y][0], 0, y))  # WEST side
        seen[y][ncolumns - 1] = True
        q.put(Cell(heights[y][ncolumns - 1], ncolumns - 1, y))  # EAST

    for x in range(ncolumns):
        seen[0][x] = True
        q.put(Cell(heights[0][x], x, 0))  # NORTH side
        seen[nrows - 1][x] = True
        q.put(Cell(heights[nrows - 1][x], x, nrows - 1))  # SOUTH

    # visit all cells once starting with cells with a minimum water level
    total = 0
    while not q.empty():
        cell = q.get()
        for dx, dy in [NORTH, SOUTH, WEST, EAST]:
            x = cell.x + dx
            y = cell.y + dy
            if 0 <= y < nrows and 0 <= x < ncolumns and not seen[y][x]:
                seen[y][x] = True
                q.put(Cell(max(cell.level, heights[y][x]), x, y))
                total += max(0, cell.level - heights[y][x])

    return total

if __name__ == "__main__":
    import sys
    heights = [[int(n) for n in line.split()]
               for line in sys.stdin if line.strip()]
    print(max_water_heldover_minheap(heights))
