Ocean Currents
Time limit1sMemory limit256 MB
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 and , 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 lines contains exactly characters, each a digit from to inclusive. The digit means the current flows north (up in the grid, in the direction of decreasing row number), means northeast, means east (in the direction of increasing column number), means southeast, and so on clockwise:
7 0 1
\|/
6-*-2
/|\
5 4 3
The line after the grid contains a single integer , the number of trips to be made, which is at most 50. Each of the next lines describes a trip with four integers , , , , 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.