namespace AtCoder; #nullable enable using System.Numerics; static class Extensions { public static T[] Repeat(this int time, Func F) => Enumerable.Range(0, time).Select(_ => F()).ToArray(); } class AtCoder { object? Solve() { var h = Int(); var w = Int(); var a = new int[h + 2, w + 2]; var d = new Dictionary>(); for (var i = 1; i <= h; i++) for (var j = 1; j <= w; j++) { var x = Int(); a[i, j] = x; if (d.TryGetValue(x, out var ll)) ll.Add((i, j)); else d[x] = new List<(int, int)>(){ (i, j) }; } var kz = new List(d.Keys); kz.Sort(); kz.Reverse(); var ans = 0; var g = new int[h + 2, w + 2]; var moves = new[]{ (-1, 0), (0, -1), (0, 1), (1, 0) }; foreach (var k in kz) { var l = d[k]; foreach (var (i, j) in l) { var y = 0; foreach (var (di, dj) in moves) { var ni = i + di; var nj = j + dj; if (a[ni, nj] != a[i, j]) y = Math.Max(y, g[ni, nj] + 1); } g[i, j] = y; ans = Math.Max(ans, y); } } return ans; } public static void Main() => new AtCoder().Run(); public void Run() { var res = Solve(); if (res != null) { if (res is bool yes) res = yes ? "Yes" : "No"; sw.WriteLine(res); } sw.Flush(); } string[] input = Array.Empty(); int iter = 0; readonly StreamWriter sw = new(Console.OpenStandardOutput()) { AutoFlush = false }; #pragma warning disable IDE0051 string String() { while (iter >= input.Length) (input, iter) = (Console.ReadLine()!.Split(' '), 0); return input[iter++]; } T Input() where T : IParsable => T.Parse(String(), null); int Int() => Input(); void Out(object? x, string? separator = null) { separator ??= Environment.NewLine; if (x is System.Collections.IEnumerable obj and not string) { var firstLine = true; foreach (var item in obj) { if (!firstLine) sw.Write(separator); firstLine = false; sw.Write(item); } } else sw.Write(x); sw.WriteLine(); } #pragma warning restore IDE0051 }