Ocean Currents

Time limit1sMemory limit256 MB

Summary
Given a grid where each cell has a current direction, find the minimum energy to travel between two cells when following the current is free and any other of the eight moves costs one.
Level

Medium7 of 10

Topics
Graph, Shortest path, BFS, Implementation
Solved
No attempts yet

Problem

For a boat on a large body of water, strong currents can be dangerous, but with careful planning they can be harnessed to help the boat reach its destination. Your job is to help with that planning.

At each location, the current flows in some direction. The captain can either go with the flow of the current, using no energy, or move one square in any other direction at a cost of one unit of energy. The boat always moves in one of eight directions: north, south, east, west, northeast, northwest, southeast, southwest. The boat cannot leave the boundary of the lake. Help the captain devise a strategy to reach the destination with the minimum energy consumption.

Input

The lake is represented as a rectangular grid. The first line of input contains two integers rr and cc, the number of rows and columns in the grid. The grid has at most 1000 rows and at most 1000 columns. Each of the next rr lines contains exactly cc characters, each a digit from 00 to 77 inclusive. The digit 00 means the current flows north (up in the grid, in the direction of decreasing row number), 11 means northeast, 22 means east (in the direction of increasing column number), 33 means southeast, and so on clockwise:

7 0 1
 \|/
6-*-2
 /|\
5 4 3

The line after the grid contains a single integer nn, the number of trips to be made, which is at most 50. Each of the next nn lines describes a trip with four integers rsr_s, csc_s, rdr_d, cdc_d, giving the row and column of the starting point and of the destination. Rows and columns are numbered starting from 1.

Output

For each trip, output a line containing a single integer: the minimum number of energy units needed to get from the starting point to the destination.

Examples1

  1. Example 1

    Input
    5 5
    04125
    03355
    64734
    72377
    02062
    3
    4 2 4 2
    4 5 1 4
    5 3 3 4
    
    Expected output
    0
    2
    1