Under construction

Still being built. Things may change

A Walk Through Brooklyn

Time limit2sMemory limit1024 MB

Summary
Pick a walk from the north edge to the south edge along house boundaries that splits the grid area into two parts with the smallest difference.
Level

Hard9 of 10

Topics
Graph, Dynamic programming, Implementation
Solved
No attempts yet

Problem

Miles Morales walks through Brooklyn. Seen from a bird's eye view, Brooklyn looks like a grid field of n×mn \times m cells, whose vertical sides are parallel to the north-south direction. Each cell belongs to a house. Houses are regions of cells connected by sides. Every unit segment on the boundary of the field or between two different houses is a road. Miles starts his walk on the northern boundary of Brooklyn. He moves along the roads to the west, east, or south. He never walks along the same road twice, even in opposite directions. He keeps walking until he reaches the southern boundary of Brooklyn. Miles's route divides Brooklyn into two parts: the part east of the route and the part west of it. Miles wants to know the minimum possible difference between the areas of these two parts. Help him answer this question.

Input

The first line contains two integers nn and mm, the size of the field (1≤n,m≤3001 \le n, m \le 300).

The next nn lines each contain mm uppercase Latin letters that describe Brooklyn. Side-connected cells with the same letter form one house.

Output

Print one integer, the minimum possible difference between the areas of the two parts that Miles's route divides Brooklyn into.

Hint

The picture for the first test. Houses are shapes of different colors, and roads are the black segments. A possible route of Miles is drawn as a red dashed line.

The picture for the second test.

Examples2

  1. Example 1

    Input
    3 3
    ABB
    BAB
    AAB
    
    Expected output
    1
    
  2. Example 2

    Input
    2 3
    AAA
    BBB
    
    Expected output
    0