Building a ranch

Given an M by N grid with trees and rocks as obstacles, find the side length of the largest square subgrid that contains no obstacle.

Medium5Dynamic programmingMatrixArrayPrefix sumInterviewNo attempts yetTime limit1sMemory limit512 MB

Problem

Mr. Land wants to spend his retirement money on a plot of land and build a ranch on it. The plot he was shown is a rectangle, mostly open field, with trees that are hard to cut down and rocks that cannot be cleared scattered across it.

The ranch is a single square, and no tree or rock may stand inside it. Mr. Land wants that square to be as large as possible.

The plot is MM meters tall and NN meters wide. Cut it into a grid of 1 meter cells and write it as an M×NM \times N matrix. In the matrix, 0 means open field, 1 means a tree, and 2 means a rock.

Find the side length LL of the largest square ranch that can be built. If the plot has no open field cell at all, LL is 0.

Input

The first line contains MM and NN, separated by a space.

Each of the next MM lines contains NN integers separated by spaces. Each value is 0, 1, or 2.

  • 1M10001 \le M \le 1000
  • 1N10001 \le N \le 1000

Output

Print the side length LL of the largest square ranch on one line.