The Carpenter
Time limit2sMemory limit128 MB
Cut two non-overlapping diagonal triangles from an n by m black-and-white board and glue them into the largest square with alternating colors.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Matrix, Prefix sum
- Solved
- No attempts yet
Problem
Byteasar wants to play a game of checkers, but he cannot find his chessboard. All he found is a wooden board of size , divided into equally sized square fields. Each field is painted white or black, and the colours are not necessarily arranged in a proper chessboard pattern.
Byteasar decided to put his carpentry experience to use and cut a chessboard out of the wood with a saw. A chessboard here is a square built from square fields in which every two fields sharing a side have different colours. A square has no pair of fields sharing a side, so it counts as a chessboard too.
The board might not contain a square of the size he wants. So he decided to cut out two triangular pieces and glue them together into a chessboard. The two pieces must not overlap, but he may turn them around in any way after cutting them out.
A piece is cut like this. Pick a square area of the board with side fields and saw along one of its diagonals. The two legs of the resulting triangle run along field boundaries and the hypotenuse runs through field corners, so every field the hypotenuse crosses is split into two halves. Gluing two such pieces along their hypotenuses gives a square. Two halves that meet on the hypotenuse become one field of the finished square, so they must have the same colour.
The two pieces must not overlap. Two different pieces each taking one half of a field the saw passed through does not count as overlapping. The figure below shows a board of size and two triangles that glue together into a chessboard of size .

Find the largest chessboard size Byteasar can obtain this way.
Input
The first line contains two integers and , the size of the board ().
Each of the next lines contains integers. The -th number in the -th line is the colour of the field where row meets column , where is a white field and is a black field (, ).
Output
Print one integer, the number of fields along one side of the largest chessboard that can be made by cutting out two triangular pieces and gluing them together.