import sys sys.setrecursionlimit(5*10**5) input = sys.stdin.readline import pypyjit pypyjit.set_param('max_unroll_recursion=-1') from collections import defaultdict, deque, Counter from heapq import heappop, heappush from bisect import bisect_left, bisect_right from math import gcd n,m = map(int,input().split()) d = [[-1] + list(map(int,input().split())) for i in range(n)] for i in range(n): d[i].sort() m+= 1 _ = [i for i in range(m)] l = -1 r = 10**9+10 while r-l > 1: mid = (r+l)//2 dp = _[::1] for i in range(1, n): dd = d[i] new = [0]*(m) ll = 0 rr = 0 for j in range(1,m): new[j] = new[j-1] bot =max(1, d[i][j] - mid) top = d[i][j] while ll < m-1 and d[i-1][ll+1] < bot: ll += 1 while rr < m-1 and d[i-1][rr+1] <= top: rr += 1 if rr == m: break tmp = dp[rr] - dp[ll] if tmp > 0: new[j] += 1 dp = new if dp[-1] == 0 : l = mid else: r = mid ans = r print(ans) if ans != 10**9+10 else print(-1)