din=open("DATA5.txt","r")
dout=open("OUT5.txt","w")

for cnt in range(2):
    w,l=map(int,din.readline().split())
    grid=[]
    for i in range(w):
        grid.append(map(int,din.readline().split()))
    impos=[]
    count=0
    while 1:
        small=51
        pos=[]
        for x in range (w):
            for y in range(l):
                if grid[x][y]<small and (x,y) not in impos:
                    pos=[(x,y)]
                    small=grid[x][y]
                elif grid[x][y]==small:
                    pos.append((x,y))
        points=[(1,0),(0,1),(-1,0),(0,-1)]
        vals={}
        connected=[]
        for x1,y1 in pos:
            minwall=100
            viable=True
            for a,b in points:
                x=x1+a
                y=y1+b
                if x<0 or x>=w or y<0 or y>=l:
                    vals[(x1,y1)]=-1
                    impos.append((x1,y1))
                    break
                else:
                    if (x,y) in pos:
                        if (x1,y1,x,y) not in connected:
                            connected.append((x1,y1,x,y))
                    else:
                        if grid[x][y]<minwall:
                            minwall=grid[x][y]
            if (x1,y1)not in vals:
                vals[(x1,y1)]=minwall
            
        for x1,y1,x2,y2 in connected:
            m=min(vals[(x1,y1)],vals[(x2,y2)])
            if m==-1:
                impos.append((x1,y1))
                impos.append((x2,y2))
            vals[(x1,y1)]=m
            vals[(x2,y2)]=m
        ct=True
        for x,y in pos:
            if vals[(x,y)]!=-1:
                ct=False
                count+=vals[(x,y)]-grid[x][y]
                grid[x][y]=vals[(x,y)]
        if ct:
            break
    dout.write(str(count)+"\n")
        
        

    
dout.close()
        
    
        

