Water Bottle
Time limit5sMemory limit512 MB
Given a grid of buildings, fields, and walls, find for each query the smallest water bottle that lets you walk between two given buildings.
- Level
Medium7 of 10
- Topics
- Graph, BFS, Shortest path, Union-find
- Solved
- No attempts yet
Problem
JOI's city, IOI, is known to be very hot all year round.
IOI is a rectangle divided into rows and columns of cells. Each cell is a building, a field, or a wall. There are building cells, numbered from 1 to .
JOI can enter only building cells and field cells. From a cell, JOI can move directly only to an adjacent cell that shares a side, and JOI cannot leave the city during a move.
JOI often walks between buildings for various errands. Buildings are air-conditioned, but fields are hot and sunny. Each field cell passed costs 1 unit of water. Fields have no vending machines or water fountains, so people usually carry a water bottle. A bottle of size holds at most units of water. Building cells have taps, so a bottle can be refilled to full there.
Large bottles are hard to carry, so JOI wants to use the smallest bottle possible. Write a program that finds, for each query, the minimum bottle size needed to travel between two given buildings.
You are given the map of IOI and queries. The -th query asks: what is the minimum bottle size needed to travel between buildings and ?
Input
The first line contains four integers , , , and separated by spaces. These mean that IOI has rows and columns, has building cells, and has queries.
The next lines describe the map. The -th of these lines contains a string of characters, each either . or #. The character in column is . for a building or field and # for a wall.
The next lines give the building positions. The -th line contains two integers and . Building is in column counting from the top, and row counting from the left. The corresponding cell on the map is guaranteed to be ..
The next lines each contain two integers and .
Output
Print lines. On line , print the minimum bottle size needed to travel between buildings and . If the trip is impossible, print -1. If the trip can be made without passing any field cell, print 0.
Constraints
- for all
- for all
- for
- for all