Task 13

grid0 (256000 kilobytes, 2000 milliseconds)

Submissions: 0 · Accepted: 0

Submit code

Statement

Problem: Painting the Grid

Problem Description

You are given a 2D grid with **n** rows and **m** columns. Initially, all cells in the grid are white, except for a single cell **(R₀, C₀)** which is already painted black.

You will receive **n × m - 1** queries. In each query, you are given a cell **(Rᵢ, Cᵢ)** that is currently white. Your task is to find the shortest Manhattan distance from this cell to any cell that is currently black. After computing this distance, the queried cell is painted black.

The Manhattan distance between two cells **(x₁, y₁)** and **(x₂, y₂)** is defined as |x₁ - x₂| + |y₁ - y₂|.

You may process the queries in any order (offline solution is allowed). Your goal is to answer all queries efficiently.

Input Format

Output Format

For each query, output a single integer — the shortest Manhattan distance from the queried cell to any black cell at the time of the query.

Constraints

Examples

Example 1

**Input:**

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

**Output:**

2
2
2
2
1
1
1
1

**Explanation:**

Example 2

**Input:**

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

**Output:**

1
4
1
2
3
2
1

Notes

1. The distance from the cached BFS (precomputed distances from all black cells at the time of the last BFS).
2. The distances to a small list of recently added black cells (size ≤ √(n×m)).

When the list of recent black cells reaches √(n×m), clear it and run a new multi-source BFS from all black cells to update the cache.

Sample test

Input
3 3
1 1
0 0
0 2
2 0
2 2
0 1
1 0
1 2
2 1
Output
2
2
2
2
1
1
1
1