#pragma GCC target("avx") #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #include using namespace std; int main() { cin.tie(0); ios::sync_with_stdio(false); int N, M; cin >> N >> M; vector> D(N, vector(M)); for( int i = 0; i < N; i++ ) { for( int j = 0; j < M; j++ ) { cin >> D[i][j]; } sort(D[i].begin(), D[i].end()); } constexpr int INF = 1<<30; vector> dp(N, vector(M, INF)); for( int i = 0; i < N-1; i++ ) { for( int j = 0; j < M; j++ ) { for( int k = 0; k < M; k++ ) { if( D[i+1][k] < D[i][j] || ( i > 0 && dp[i][j] == INF ) ) continue; dp[i+1][k] = min({dp[i+1][k], dp[i][j], abs(D[i+1][k]-D[i][j])}); } } } int me = *min_element(dp[N-1].begin(), dp[N-1].end()); cout << ( me == INF ? -1 : me ) << endl; }