#K47472. Calculate Shortest Manhattan Distances

    ID: 28206 Type: Default 1000ms 256MiB

Calculate Shortest Manhattan Distances

Calculate Shortest Manhattan Distances

You are given a grid with M rows and N columns. Each cell of the grid is represented by a character: a 'B' indicates a building and a '.' indicates an open space. In addition, you are provided with the coordinates (r, c) of a specific building in this grid.

Your task is to compute the shortest Manhattan distances from this specified building to all blocks that are located in the same row or the same column. The Manhattan distance between two cells at coordinates (r1, c1) and (r2, c2) is given by:

\( d = |r1 - r2| + |c1 - c2| \)

Since the blocks you are checking share either the same row or the same column as the building, the formula simplifies to:

  • If in the same row: \( d = |j - c| \) for each column index \( j \).
  • If in the same column: \( d = |i - r| \) for each row index \( i \), excluding the building's own cell.

You should output the results as a series of triples \( (i, j, d) \). First, output all triples from the specified row in order from column 0 to \( N-1 \). Then, output the triples from the specified column (for all rows except \( r \)) in order from row 0 to \( M-1 \).

inputFormat

The first line of input contains two space-separated integers: M and N, the number of rows and columns of the grid.

The next M lines each contain a string of length N representing a row of the grid.

The final line contains two space-separated integers: r and c, representing the row and column indices of the specific building.

outputFormat

Output exactly N + M - 1 lines. The first N lines correspond to the cells in the given row r, and each line should contain three space-separated integers: r, j, and the Manhattan distance \(|j - c|\) for \(j = 0, 1, \ldots, N-1\).

The following M - 1 lines correspond to the cells in the given column c (excluding the one at row r). Each line should contain three space-separated integers: i, c, and the Manhattan distance \(|i - r|\) for all \(i = 0, 1, \ldots, M-1\) where \(i \neq r\).

## sample
5 5
.B...
.....
.....
...B.
.....
2 1
2 0 1

2 1 0 2 2 1 2 3 2 2 4 3 0 1 2 1 1 1 3 1 1 4 1 2

</p>