#K15421. Burning Forest

    ID: 24353 Type: Default 1000ms 256MiB

Burning Forest

Burning Forest

You are given a forest represented as a grid of dimensions \(M \times N\). Each cell in the grid contains either a tree, indicated by 1, or is empty, indicated by 0. A fire starts from a given cell, and every minute the fire spreads to any adjacent cell (up, down, left, right) that contains a tree.

Your task is to determine the minimum number of minutes required to burn all the trees in the forest. If there exists at least one tree that the fire cannot reach (i.e. it is isolated from the starting point), then output \(-1\).

Note: The grid is 0-indexed and the starting cell is guaranteed to be within bounds. Use an efficient breadth-first search (BFS) strategy to solve the problem.

inputFormat

The input is given via standard input (stdin) and has the following format:

M N
row1 (N integers separated by spaces)
row2
...
rowM
start_x start_y

Here, \(M\) and \(N\) denote the number of rows and columns of the grid, respectively. Each of the following \(M\) lines contains \(N\) integers (either 0 or 1) that represent the forest grid. The last line contains two integers representing the starting cell coordinates (row and column, 0-indexed) of the fire.

outputFormat

Output a single integer via standard output (stdout): the minimum number of minutes required to burn the entire forest. If there is at least one tree that is unreachable by the fire, output \(-1\).

## sample
3 3
1 1 1
1 1 0
0 1 1
0 0
4