Under construction

Still being built. Things may change

Excursions

Time limit3sMemory limit1024 MB

Summary
Given a grid of nice and ugly cells, answer Q queries with the shortest 4-directional path between two cells that avoids ugly cells, or -1 if none exists.
Level

Medium5 of 10

Topics
BFS, Graph, Matrix
Solved
No attempts yet

Problem

Kasandra finally opened her first travel agency. Her trips are limited to Croatia for now, which we can picture as a table of size N×MN \times M. Some cells are nice and marked with ., while the others are ugly and marked with #. Tourists can move in only four basic directions: up, down, left, and right.

Kasandra currently has QQ planned trips. For each one, she wants the minimum number of steps from the starting point to the final destination without passing through any ugly cell. If the destination cannot be reached from the starting point, print −1-1.

Input

The first line contains the natural numbers NN (1≤N≤3001 \le N \le 300), MM (1≤M≤3001 \le M \le 300), and QQ (1≤Q≤100 0001 \le Q \le 100\,000).

The next NN lines describe the table as explained in the problem.

The next QQ lines each contain four numbers AiA_i, BiB_i, CiC_i, DiD_i (1≤Ai,Ci≤N1 \le A_i, C_i \le N, 1≤Bi,Di≤M1 \le B_i, D_i \le M). The pair (Ai,Bi)(A_i, B_i) is the row and column of the starting point, and (Ci,Di)(C_i, D_i) is the row and column of the destination.

Output

Print QQ lines. The ii-th line contains the distance between the starting point and the destination of the ii-th trip.

Examples2

  1. Example 1

    Input
    5 6 4
    #...#.
    ......
    #.#.#.
    ....#.
    ......
    4 1 4 1
    2 4 1 3
    5 1 3 2
    5 1 4 1
    
    Expected output
    0
    2
    3
    1
    
  2. Example 2

    Input
    4 4 3
    ....
    ....
    ##..
    .#..
    4 1 3 3
    2 3 1 1
    1 4 4 1
    
    Expected output
    -1
    3
    -1