import sys input = sys.stdin.readline from operator import itemgetter H,W=map(int,input().split()) A=[list(map(int,input().split())) for i in range(H)] # dinic法 from collections import defaultdict,deque V=H*W*3+2 start=V-2 goal=V-1 EDGE=[defaultdict(int) for i in range(V)] now=H*W-1 for i in range(H): L=[] for j in range(W): L.append((A[i][j],i*W+j)) L.sort(key=itemgetter(0)) for k in range(len(L)): if L[k][0]==0: continue if k-1>=0 and L[k][0]==L[k-1][0]: EDGE[start][now]=1 EDGE[now][L[k][1]]=1000000 else: now+=1 EDGE[start][now]=1 EDGE[now][L[k][1]]=1000000 for j in range(W): L=[] for i in range(H): L.append((A[i][j],i*W+j)) L.sort(key=itemgetter(0)) for k in range(len(L)): if L[k][0]==0: continue if k-1>=0 and L[k][0]==L[k-1][0]: EDGE[now][goal]=1 EDGE[L[k][1]][now]=1000000 else: now+=1 EDGE[now][goal]=1 EDGE[L[k][1]][now]=1000000 ANS=0 while True: # まずBFSする DIS=[-1]*V Q=deque([start]) DIS[start]=0 EDGE2=[[] for i in range(V)] while Q: x=Q.popleft() for to in EDGE[x]: if EDGE[x][to]==0: continue if DIS[to]==-1: DIS[to]=DIS[x]+1 Q.append(to) EDGE2[x].append(to) elif DIS[to]==DIS[x]+1: EDGE2[x].append(to) if DIS[goal]==-1: break # BFSしたときのEDGEを使ってDFSする MINCOST=[float("inf")]*V NOW=start ROUTE=[-1]*V while NOW!=-1: # DFS cost=MINCOST[NOW] if NOW==goal: ANS+=cost i=goal while i!=start: # goalからたどり,Routeを使ってEDGEの更新 j=ROUTE[i] if EDGE[j][i]==cost: NOW=j EDGE2[j].pop() EDGE[j][i]-=cost # 使ったルートをいけなく更新 MINCOST[j]-=cost EDGE[i][j]+=cost # 逆向きに進めるようにする. i=j continue if EDGE2[NOW]: to=EDGE2[NOW][-1] ROUTE[to]=NOW MINCOST[to]=min(cost,EDGE[NOW][to]) NOW=to else: if NOW==start: break EDGE2[ROUTE[NOW]].pop() NOW=ROUTE[NOW] print(ANS)