Under construction

Still being built. Things may change

Game Board

Interview

Time limit1sMemory limit1024 MB

Summary
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

NN rows and MM columns of grid. Each cell is empty or holds piece 1 or piece 2. For convenience, the cell in row XX and column YY (1≤X≤N,1≤Y≤M1 \leq X \leq N, 1 \leq Y \leq M) is written (XX, YY). The top-left cell is (1,1)(1, 1), and the bottom-right cell is (N,M)(N, M).

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 KK, 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 KK by KK 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 (X,Y)(X, Y), the center is at (X+K−12,Y+K−12)(X+\frac{K-1}{2}, Y+\frac{K-1}{2}). The distance between cells (X1,Y1)(X_1, Y_1) and (X2,Y2)(X_2, Y_2) is ∣X1−X2∣+∣Y1−Y2∣|X_1 - X_2| + |Y_1 - Y_2|. For example, the distance between (1,3)(1, 3) and (5,1)(5, 1) is (5−1)+(3−1)(5-1) + (3-1), which is 66.

The figure below shows a 44 by 55 grid, and Juwon and Junwon want to pick a 33 by 33 subgrid inside it.

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

If the subgrid has top-left (2,1)(2, 1) and bottom-right (4,3)(4, 3), the sum of distances for piece 1 to the center is 0+1=10+1=1, and the sum for piece 2 is 1+1=21+1 = 2. The difference in advantage is 11. No subgrid of the NN by MM grid gives a difference smaller than 11, so the answer is 11.

Find the smallest difference in advantage over all subgrids Juwon and Junwon can choose.

Input

The first line contains NN, MM, and KK, separated by spaces.

The next NN lines each contain a string of length MM that describes the grid. The string consists of ., 1, and 2, with these meanings:

  • . : an empty cell
  • 1 : a cell with piece 1
  • 2 : a cell with piece 2

Output

Print the smallest possible difference in advantage on the first line.

Constraints

  • All given numbers are integers.
  • 1≤N,M≤5001 \leq N, M \leq 500
  • 1≤K≤min⁡(N,M)1 \leq K \leq \min(N, M)
  • KK is odd.
  • The grid consists of ., 1, and 2.

Examples2

  1. Example 1

    Input
    4 5 3
    .111.
    .2.2.
    .111.
    .2.2.
    
    Expected output
    1
    
  2. Example 2

    Input
    3 3 3
    ...
    ...
    ...
    
    Expected output
    0