#K68242. Minimum Perimeter Garden Bed

    ID: 32821 Type: Default 1000ms 256MiB

Minimum Perimeter Garden Bed

Minimum Perimeter Garden Bed

You are given a garden grid with N rows and M columns. Each cell in the grid is either empty (denoted by .) or contains a herb (denoted by H). Your task is to determine the minimum perimeter of a rectangular garden bed that covers all the herbs in the grid. If there are no herbs, the perimeter is 0.

The perimeter of a rectangle that has height h and width w is given by the formula:

\(2 \times (h + w)\)

The rectangle must be aligned with the grid, and its boundaries must enclose every cell that contains a herb. For example, if the grid is as follows:

.......
..H....
.HH....
...H...
.......

the smallest rectangle that encloses all the herbs has a perimeter of 12.

inputFormat

The input is read from standard input (stdin) and has the following format:

  1. The first line contains two space-separated integers N and M representing the number of rows and columns respectively.
  2. The following N lines each contain a string of length M, representing a row of the garden grid. Each character in the string is either H (a herb) or . (an empty cell).

outputFormat

Output a single integer to standard output (stdout) which is the minimum perimeter of a rectangle that encloses all cells containing a herb. If there are no herbs in the grid, output 0.

## sample
5 7
.......
..H....
.HH....
...H...
.......
12