#K3286. Maximum Distance to Park

    ID: 24959 Type: Default 1000ms 256MiB

Maximum Distance to Park

Maximum Distance to Park

You are given a square grid of size \(n \times n\) representing a city. Each cell in the grid is either a building (denoted by the character 'B') or a park (denoted by 'P'). Your task is to compute the maximum distance from any building to the nearest park.

The distance between two cells is defined as the number of moves required to reach one from the other if in one move you can travel to an adjacent cell in the four cardinal directions (up, down, left, right). Formally, given two cells (r1, c1) and (r2, c2), the distance is computed using the Manhattan distance formula:

[ d((r1,c1),(r2,c2)) = |r1 - r2| + |c1 - c2| ]

If the grid contains no building or no park (i.e. the answer is not computable), output -1.

Note: The grid is provided from the standard input and the answer should be printed to the standard output.

inputFormat

The first line of the input contains an integer \(n\) which represents the dimensions of the square grid. Each of the next \(n\) lines contains a string of \(n\) characters, each being either 'B' (building) or 'P' (park), representing a row of the grid.

For example:

3
BBP
PBB
BPB

outputFormat

Output a single integer: the maximum distance from any building to the nearest park. If the grid has either no parks or no buildings (or if all cells are parks), output -1.

## sample
3
BBP
PBB
BPB
1

</p>