Invasion of the Milkweed

Interview

Time limit1sMemory limit128 MB

Summary
Spread milkweed from a start cell to all eight neighbors each week and report the week it covers the last non-boulder cell.
Level

Easy3 of 10

Topics
BFS, Graph, Matrix, Simulation
Solved
No attempts yet

Problem

Farmer John has always done his best to keep his pastures full of luscious, delicious, healthy grass for his cows. He has lost this battle, though: the invasive milkweed has taken a foothold in the northwest corner of his farm.

The pasture is partitioned into a rectangular grid of height YY (1≤Y≤1001 \le Y \le 100) and width XX (1≤X≤1001 \le X \le 100). Cell (1,1)(1, 1) is the lower-left corner, so the grid uses ordinary (x,y)(x, y) coordinates. The milkweed starts growing in cell (Mx,My)(M_x, M_y).

Each week the milkweed spreads from every cell it already occupies into all of the (up to eight) surrounding non-boulder cells — the four orthogonal neighbors and the four diagonal neighbors. After spending just one week in a cell, the milkweed is ready to spread out of that cell as well.

Bessie wants to graze for as long as she can before the milkweed takes over, so she wonders how long the pasture will last. If the milkweed occupies cell (Mx,My)(M_x, M_y) at week 00, in which week does it finish covering every non-boulder cell of the pasture? (For every input in this problem, the milkweed always ends up covering the whole pasture.)

The pasture is drawn with . for grass and * for a boulder. For example, with X=4X = 4 and Y=3Y = 3:

....
..*.
.**.

If the milkweed starts in the lower-left corner (row 11, column 11), the map fills in as shown below. The five snapshots are weeks 00 through 44 from left to right, and M marks a milkweed-covered cell:

....  ....  MMM.  MMMM  MMMM
..*.  MM*.  MM*.  MM*M  MM*M
M**.  M**.  M**.  M**.  M**M

The milkweed has covered the entire field after 44 weeks.

Input

  • Line 1: Four space-separated integers XX, YY, MxM_x, and MyM_y.
  • Lines 2 through Y+1Y+1: The pasture map, given from the top row down to the bottom row. Line 22 is the top row (row YY) and line Y+1Y+1 is the bottom row (row 11); each line contains XX characters, . for grass and * for a boulder. Because (1,1)(1, 1) is the lower-left corner, line kk (for 2≤k≤Y+12 \le k \le Y+1) describes row Y+2−kY+2-k.

Output

  • Line 1: A single integer: the week number in which the milkweed covers the last remaining non-boulder cell of the pasture.

Examples1

  1. Example 1

    Input
    4 3 1 1
    ....
    ..*.
    .**.
    
    Expected output
    4