import java.io.*;
import java.util.*;

public class sherlocked_pk {

	void solve() throws IOException {
		int n = nextInt();
		int m = nextInt();
		int[][] a = new int[n][m];
		int[][] prev = new int[n][m];
		int[] first = new int[n * m * 10];
		Arrays.fill(first, -1);
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				a[i][j] = nextInt() - 1;
				prev[i][j] = first[a[i][j]];
				first[a[i][j]] = i * 1000 + j;
			}
		}

		int[][] dp = new int[n][m];
		int ans = 0;
		for (int t = 0; t < n * m * 10; t++) {
			int x = first[t];
			while (x != -1) {
				int i = x / 1000;
				int j = x % 1000;
				dp[i][j] = 1;
				if (i > 0 && a[i - 1][j] == t - 1)
					dp[i][j] = Math.max(dp[i][j], dp[i - 1][j] + 1);
				if (i < n - 1 && a[i + 1][j] == t - 1)
					dp[i][j] = Math.max(dp[i][j], dp[i + 1][j] + 1);

				if (j > 0 && a[i][j - 1] == t - 1)
					dp[i][j] = Math.max(dp[i][j], dp[i][j - 1] + 1);
				if (j < m - 1 && a[i][j + 1] == t - 1)
					dp[i][j] = Math.max(dp[i][j], dp[i][j + 1] + 1);
				x = prev[i][j];
				ans = Math.max(ans, dp[i][j]);
			}
		}
		out.println(ans);
	}

	BufferedReader br;
	StringTokenizer st;
	PrintWriter out;

	void run() {
		try {
			// br = new BufferedReader(new InputStreamReader(System.in));
			// out = new PrintWriter(System.out);

			br = new BufferedReader(new FileReader(new File("sherlocked.in")));
			out = new PrintWriter("sherlocked.out");
			solve();

			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new sherlocked_pk().run();
	}

	String nextToken() throws IOException {
		while ((st == null) || !st.hasMoreTokens())
			st = new StringTokenizer(br.readLine());
		return st.nextToken();
	}

	int nextInt() throws NumberFormatException, IOException {
		return Integer.parseInt(nextToken());
	}

	double nextDouble() throws NumberFormatException, IOException {
		return Double.parseDouble(nextToken());
	}

	long nextLong() throws NumberFormatException, IOException {
		return Long.parseLong(nextToken());
	}
}
