Game Board
InterviewTime limit1sMemory limit1024 MB
Find the K by K subgrid (K odd) where the gap between the two players' summed Manhattan distances to the center is smallest.
- Level
Medium5 of 10
- Topics
- Prefix sum, Matrix, Implementation
- Solved
- No attempts yet
Statement
rows and columns of grid. Each cell is empty or holds piece 1 or piece 2. For convenience, the cell in row and column () is written (, ). The top-left cell is , and the bottom-right cell is .
Juwon and Junwon want to play a game on this grid. Juwon takes piece 1, and Junwon takes piece 2. The game needs a square grid with odd side length , so they pick a part of the grid and play only inside it.
To keep the game fair, Juwon and Junwon want to choose, among all by subgrids they can choose, the one where the difference in advantage is smallest. A player's advantage is the sum of distances from the center of the chosen subgrid to that player's pieces inside it. If the top-left cell of the chosen subgrid is , the center is at . The distance between cells and is . For example, the distance between and is , which is .
The figure below shows a by grid, and Juwon and Junwon want to pick a by subgrid inside it.

When the subgrid has top-left and bottom-right , the sum of distances from piece 1 to the center is , and the sum for piece 2 is . The difference in advantage is .

If the subgrid has top-left and bottom-right , the sum of distances for piece 1 to the center is , and the sum for piece 2 is . The difference in advantage is . No subgrid of the by grid gives a difference smaller than , so the answer is .

Find the smallest difference in advantage over all subgrids Juwon and Junwon can choose.
Input
The first line contains , , and , separated by spaces.
The next lines each contain a string of length that describes the grid. The string consists of ., 1, and 2, with these meanings:
.: an empty cell1: a cell with piece 12: a cell with piece 2
Output
Print the smallest possible difference in advantage on the first line.
Constraints
- All given numbers are integers.
- is odd.
- The grid consists of
.,1, and2.