#K11981. Minimum Total Manhattan Distance

    ID: 23589 Type: Default 1000ms 256MiB

Minimum Total Manhattan Distance

Minimum Total Manhattan Distance

You are given a grid of size r × c where each cell is either a road represented by '.' or a building represented by 'B'. Your task is to find an empty cell (i.e. a road cell) such that the sum of the Manhattan distances from this cell to every building is minimized. The Manhattan distance between two points \((r_1, c_1)\) and \((r_2, c_2)\) is given by:

[ |r_1 - r_2| + |c_1 - c_2| ]

If there are fewer than two buildings in the grid, output 0. Otherwise, print the minimal total distance from a road cell to all buildings. It is guaranteed that there is at least one road cell if there are at least two buildings.

inputFormat

The first line contains two space-separated integers r and c, representing the number of rows and columns of the grid respectively.

The following r lines each contain a string of length c consisting only of the characters 'B' and '.', representing the grid.

outputFormat

Output a single integer — the minimal total Manhattan distance from a road cell ('.') to all the buildings ('B'). If there are zero or one building, output 0.

## sample
3 3
B..
.BB
...
4