import bisect def solve(): h, w, n = map(int, input().split()) a = [list(map(int, input().split())) for _ in range(h)] for i in range(h): for j in range(w): a[i][j] -= 1 dp = [0 for _ in range(n + 1)] dp[0] = 1 nxt = [n for _ in range(n + 1)] for i in range(h - 1): for j in range(w): x = min(a[i][j], a[i + 1][j]) y = max(a[i][j], a[i + 1][j]) if x != y: nxt[x] = min(nxt[x], y) for i in range(h): for j in range(w - 1): x = min(a[i][j], a[i][j + 1]) y = max(a[i][j], a[i][j + 1]) if x != y: nxt[x] = min(nxt[x], y) for i in range(n): dp[i + 1] = max(dp[i + 1], dp[i]) if nxt[i] != n: dp[nxt[i]] = max(dp[nxt[i]], dp[i] + 1) print(dp[n]) if __name__ == '__main__': solve()