import sys input = sys.stdin.buffer.readline sys.setrecursionlimit(10 ** 7) U = 5 * 10 ** 5 + 1 class BipartiteMatching: def __init__(self, N, M): self.N = N self.M = M self.pairA = [-1] * N self.pairB = [-1] * M self.edge = [[] for _ in range(N)] self.was = [0] * N self.iter = 0 def add(self, s, t): self.edge[s].append(t) def _DFS(self, s): self.was[s] = self.iter for t in self.edge[s]: if self.pairB[t] == -1: self.pairA[s] = t self.pairB[t] = s return True for t in self.edge[s]: if self.was[self.pairB[t]] != self.iter and self._DFS(self.pairB[t]): self.pairA[s] = t self.pairB[t] = s return True return False def solve(self): res = 0 while True: self.iter += 1 found = 0 for i in range(self.N): if self.pairA[i] == -1 and self._DFS(i): found += 1 if not found: break res += found return res H, W = map(int, input().split()) P = [[] for _ in range(U)] for i in range(H): for j, a in enumerate(map(int, input().split())): P[a].append((i, j)) ans = 0 for i in range(1, U): if not P[i]: continue X, Y = zip(*P[i]) xtoi = {x: j for j, x in enumerate(sorted(set(X)))} ytoi = {y: j for j, y in enumerate(sorted(set(Y)))} match = BipartiteMatching(len(xtoi), len(ytoi)) for a, b in P[i]: match.add(xtoi[a], ytoi[b]) ans += match.solve() # print(i, match.solve()) print(ans)