from collections import * from itertools import * from functools import * from heapq import * import sys,math input = sys.stdin.readline class Dinic: def __init__(self, n): self.n = n self.links = [[] for _ in range(n)] self.depth = None self.progress = None def add_link(self, _from, to, cap): self.links[_from].append([cap, to, len(self.links[to])]) self.links[to].append([0, _from, len(self.links[_from]) - 1]) def bfs(self, s): depth = [-1] * self.n depth[s] = 0 q = deque([s]) while q: v = q.popleft() for cap, to, rev in self.links[v]: if cap > 0 and depth[to] < 0: depth[to] = depth[v] + 1 q.append(to) self.depth = depth def dfs(self, v, t, flow): if v == t: return flow links_v = self.links[v] for i in range(self.progress[v], len(links_v)): self.progress[v] = i cap, to, rev = link = links_v[i] if cap == 0 or self.depth[v] >= self.depth[to]: continue d = self.dfs(to, t, min(flow, cap)) if d == 0: continue link[0] -= d self.links[to][rev][0] += d return d return 0 def max_flow(self, s, t): flow = 0 while True: self.bfs(s) if self.depth[t] < 0: return flow self.progress = [0] * self.n current_flow = self.dfs(s, t, float('inf')) while current_flow > 0: flow += current_flow current_flow = self.dfs(s, t, float('inf')) H,W = map(int,input().split()) A = [list(map(int,input().split())) for _ in range(H)] ans = 0 V = defaultdict(set) E = defaultdict(list) N = H*W for i in range(H): for j in range(W): a = A[i][j] V[a].add(i) V[a].add(j+N) E[a].append((i,j+N)) for k in V.keys(): if k==0: continue v = list(V[k])+[-1,2*N] v.sort() n = len(v) D = Dinic(n) conv = {v[i]:i for i in range(n)} S = set() T = set() for i,j in E[k]: S.add(conv[i]) T.add(conv[j]) D.add_link(conv[i],conv[j],1) for s in S: D.add_link(0,s,1) for t in T: D.add_link(t,n-1,1) ans += D.max_flow(0,n-1) print(ans)