#include<bits/stdc++.h>
#define taskname "C"
using namespace std;
const int INF = 1e9;
template<class T>void minimize(T& a, T b){
	if(a > b){
		a = b;
	}
}
template<class T>void maximize(T& a, T b){
	if(a < b){
		a = b;
	}
}
int n, m;
namespace sub1{
	void solve(){
		vector<vector<int>>a(n, vector<int>(m));
		for(int i = 0; i < n; i++){
			for(int j = 0; j < m; j++){
				cin >> a[i][j];
			}
		}
		int ans = INF;
		vector<int>current;
		auto play = [&] (auto&& self, int p) -> void{
			if(p == n){
				if(current[0] > 0 && current[n - 1] < m){
					int a_max = 0, b_max = 0, a_min = INF, b_min = INF;
					for(int i = 0; i < n; i++){
						for(int j = 0; j < current[i]; j++){
							maximize(a_max, a[i][j]);
							minimize(a_min, a[i][j]);
						}
						for(int j = current[i]; j < m; j++){
							maximize(b_max, a[i][j]);
							minimize(b_min, a[i][j]);
						}
					}
					minimize(ans, max(a_max - a_min, b_max - b_min));
				}
				return;	
			}
			for(int i = (current.empty() ? m : current.back()); i > -1; i--){
				current.emplace_back(i);
				self(self, p + 1);
				current.pop_back();
			}
		};
		play(play, 0);
		reverse(a.begin(), a.end());
		play(play, 0);
		cout << ans;
	}
}
namespace sub23{
	void solve(){
		
	}
}
int main(){
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	if(fopen(taskname".inp", "r")){
		freopen(taskname".inp", "r", stdin);
	}
	cin >> n >> m;
	if(n <= 10 && m <= 10){
		sub1::solve();
	}
	else{
		sub23::solve();
	}
}
Compilation message (stderr)
joioi.cpp: In function 'int main()':
joioi.cpp:64:24: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
   64 |                 freopen(taskname".inp", "r", stdin);
      |                 ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... |