cswork / OAOpen practice workspace

DoorDashOA #2

Closest DashMart

Estimated MediumJudge-ready

Topics (AI-labelled)Shortest PathsGrid Search

Grid characters: a space is a road, X is a wall, and D is a warehouse. You may only move up, down, left, or right; each query asks for the shortest distance to the nearest warehouse. A query on a wall cell, out of bounds, or with no reachable warehouse returns -1.

Input

R C Q, R lines of the character grid, and Q 0-based coordinates. Site supplement: R,C≤1000, RC≤200000, Q≤200000.

Output

Output Q distances.

Example 1

Input:

3 3 5
D  
 XX
   
0 0
0 2
2 0
1 1
9 0

Output:

0 2 2 -1 -1

Example 2

Input:

1 3 3
XDX
0 0
0 1
0 2

Output:

-1 0 -1

Example 3

Input:

2 1 2
D
X
0 0
1 0

Output:

0 -1

Editorial

Loading solution…