problems / 192

Suki's Paint Grid Coverage

easy matrix dfs bfs simulation 1000 ms · 256 MB

Suki's Paint Grid Coverage

Suki, a black curly-coated dog with a grey beard and white paws, has discovered a grid of unpainted tiles in the park. She starts painting from a specific tile and, being a curious pup, the paint spreads to all orthogonally adjacent unpainted tiles. She continues painting until all reachable tiles are covered.

Given an n × m grid where each cell is either painted (1) or unpainted (0), a starting position, determine the final state of the grid after the paint spreads, and count the total number of painted cells.

Input

The first line contains n and m (1 ≤ n, m ≤ 500), the dimensions of the grid.

The second line contains r and c (0 ≤ r < n, 0 ≤ c < m), the starting row and column (0-indexed).

The next n lines each contain m space-separated integers, either 0 or 1, representing the initial state of each cell. 0 means unpainted, 1 means already painted (obstacle).

Output

Print n lines, each containing m space-separated integers, representing the final state of the grid after the paint spreads from the starting position.

On the last line, print the total count of painted cells.

Notes

  • Paint spreads only to orthogonally adjacent cells (up, down, left, right), not diagonally.
  • If the starting cell is already painted (1), no paint spreads at all.
  • The paint spreading is instantaneous—all reachable unpainted cells become painted simultaneously from Suki's perspective.

Example 1

Input

3 3
1 1
0 0 0
0 0 0
0 0 0

Output

1 1 1
1 1 1
1 1 1
9

Example 2

Input

4 5
0 0
0 0 1 0 0
1 1 1 0 0
0 0 0 0 0
1 1 0 0 0

Output

1 1 1 0 0
1 1 1 0 0
0 0 0 0 0
1 1 0 0 0
8

Hints · reveal one at a time if you're stuck

Hint 1

Paint moves only through unpainted tiles, one orthogonal step at a time. Which standard search visits exactly the tiles that can be reached that way?

Hint 2

Search from the start tile over orthogonal neighbours that are still 0, marking each one as you reach it. If the start tile is already 1, nothing changes, and the final count includes tiles that were painted at the beginning.

report an issue Prefer your own editor? sooks prep 192 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.