import sys sys.setrecursionlimit(10**7) def I(): return int(sys.stdin.readline().rstrip()) def MI(): return map(int,sys.stdin.readline().rstrip().split()) def LI(): return list(map(int,sys.stdin.readline().rstrip().split())) def LI2(): return list(map(int,sys.stdin.readline().rstrip())) def S(): return sys.stdin.readline().rstrip() def LS(): return list(sys.stdin.readline().rstrip().split()) def LS2(): return list(sys.stdin.readline().rstrip()) from collections import deque class Dinic: def __init__(self, N, inf): self.N = N self.inf = inf self.G = [[] for _ in range(N)] self.level = [0]*N def add_edge(self, fr, to, cap): forward = [to, cap, None] forward[2] = backward = [fr, 0, forward] self.G[fr].append(forward) self.G[to].append(backward) def add_multi_edge(self, v1, v2, cap1, cap2): edge1 = [v2, cap1, None] edge1[2] = edge2 = [v1, cap2, edge1] self.G[v1].append(edge1) self.G[v2].append(edge2) def bfs(self, s): self.level = [-1]*self.N deq = deque([s]) self.level[s] = 0 while deq: v = deq.pop() lv = self.level[v] + 1 for w, cap, _ in self.G[v]: if cap > 0 and self.level[w] == -1: self.level[w] = lv deq.appendleft(w) def dfs(self, v, t, f): if v == t: return f for e in self.iter[v]: w, cap, rev = e if cap > 0 and self.level[v] < self.level[w]: d = self.dfs(w, t, min(f, cap)) if d > 0: e[1] -= d rev[1] += d return d return 0 def flow(self, s, t): flow = 0 while True: self.bfs(s) if self.level[t] == -1: return flow *self.iter, = map(iter, self.G) f = self.inf while f > 0: f = self.dfs(s, t, self.inf) flow += f H,W = MI() A = [LI() for _ in range(H)] X = [[] for _ in range(5*10**5+1)] for i in range(H): for j in range(W): a = A[i][j] X[a].append((i,j)) ans = 0 inf = 10**18 for i in range(1,5*10**5+1): if not X[i]: continue Di = Dinic(H+W+2,inf) S = H+W T = H+W+1 for j in range(H): Di.add_edge(S,j,1) for k in range(H,H+W): Di.add_edge(k,T,1) for h,w in X[i]: Di.add_edge(h,H+w,1) ans += Di.flow(S,T) print(ans)