#K85142. Smallest Distance Between Trees

    ID: 36576 Type: Default 1000ms 256MiB

Smallest Distance Between Trees

Smallest Distance Between Trees

You are given a forest represented as a grid of size \(n \times m\). Each cell in the grid is either empty ('.') or contains a tree ('T'). Your task is to determine the smallest Manhattan distance between any two trees in the grid.

The Manhattan distance between two cells \((i_1, j_1)\) and \((i_2, j_2)\) is defined as:

\[ |i_1 - i_2| + |j_1 - j_2| \]

If there are fewer than two trees on the grid, output \(-1\).

inputFormat

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

  • The first line contains two space-separated integers \(n\) and \(m\) representing the number of rows and columns of the grid.
  • Each of the next \(n\) lines contains a string of length \(m\) representing a row of the grid. Each character is either '.' (empty cell) or 'T' (a tree).

outputFormat

Output a single integer to standard output (stdout): the smallest Manhattan distance between any two trees in the grid. If there are fewer than two trees, output -1.

## sample
2 2
..
..
-1