Under construction

Still being built. Things may change

Hexagonal Tile Maze Escape

Interview

Time limit1sMemory limit1024 MB

Summary
Find the shortest path from (0,0) to (N-1, M-1) on a hex grid avoiding obstacles, and print its tile count or -1.
Level

Easy3 of 10

Topics
BFS, Graph, Matrix
Solved
No attempts yet

Section 1

Yunsu fell into a hexagonal tile maze on the way to a party, after being tricked by the nasty Jonghyun. The maze is a grid of regular hexagonal tiles with NN rows and MM columns. Compare two cells in the same column: a cell in an even-numbered row is half a cell to the right of a cell in an odd-numbered row. The figure below shows a hexagonal tile maze with N=4N=4 and M=7M=7.

Yunsu always starts at (0,0)(0,0), and the exit is always at (N−1,M−1)(N-1, M-1). Jonghyun placed KK obstacles on the tiles to block Yunsu's escape. On a tile, Yunsu can move to an adjacent tile, but cannot move onto a tile that has an obstacle. Two tiles are adjacent if they share a side.

Yunsu is in a hurry to get to the party. A shortest path is a path to the exit that passes through the fewest tiles. The starting tile is not counted, and the exit tile is counted. Find the number of tiles on the shortest path from the start to the exit.

Input

The first line contains the maze size NN and MM and the number of obstacles KK, separated by spaces.

From the second line, the next KK lines each contain the position of an obstacle (Yk,Xk)(Y_k, X_k), separated by a space. No two obstacles are at the same position. The starting tile and the exit tile never have an obstacle.

Output

Print the number of tiles on the shortest path from the start to the exit. If Yunsu cannot reach the exit, print -1.

Limits

  • 2≤N≤1 0002 \le N \le 1\,000
  • 2≤M≤1 0002 \le M \le 1\,000
  • 0≤K≤N×M−20 \le K \le N \times M - 2
  • 0≤Yk≤N−10 \le Y_k \le N - 1
  • 0≤Xk≤M−10 \le X_k \le M - 1
  • All numbers in the input are integers.

Examples3

  1. Example 1

    Input
    3 4 2
    1 1
    1 2
    
    Expected output
    4
    
  2. Example 2

    Input
    3 4 2
    0 1
    1 0
    
    Expected output
    -1
    
  3. Example 3

    Input
    4 7 12
    0 1
    0 2
    0 6
    1 1
    1 3
    1 5
    1 6
    2 1
    2 3
    2 5
    2 6
    3 2
    
    Expected output
    13