Rocky Mountain Road Trip

시간 제한2초메모리 제한2048 MB

요약
연속된 고도 변화가 오르기와 내리기를 번갈아 가야 하는 격자에서 왕처럼 이동하는 최단 경로의 길이를 구한다.
난이도

보통10점 중 7점

유형
BFS, 그래프, 최단 경로, 구현
정답자
아직 제출이 없습니다

문제

Adeline and Byron are on a road trip through the mountains. Interestingly, the roads through the mountains can be modeled as a grid of size n×mn \times m, where each cell has an integer altitude. The grid follows standard Cartesian coordinates, with the top-left corner being (1,1)(1,1) and the bottom-right corner being (n,m)(n, m).

Adeline, an adrenaline junkie, loves the ups and downs of the mountains, while Byron gets motion sick easily. After some debate, they agreed on a compromise: they must find a route from their starting position (x_0,y_0)(x\_0, y\_0) to their destination (x_f,y_f)(x\_f, y\_f) that minimizes the total distance traveled, but to make it fun for Adeline, they must alternate between gaining and losing altitude with every move. If they take a longer path than necessary, Byron will get sick.

Adeline and Byron's car can move in any of the 8 cardinal directions: North, Northeast, East, Southeast, South, Southwest, West, and Northwest. Each movement to an adjacent cell counts as a distance of 1, regardless of direction.

Help Adeline and Byron determine the minimum number of moves required to reach their destination.

입력

The first line contains two integers nn and mm (1≤n,m≤500)(1 \leq n, m \leq 500)—the dimensions of the grid.

The next nn lines each contain mm integers h_i,jh\_{i,j} (0≤h_i,j≤109)(0 \leq h\_{i,j} \leq 10^9), representing the altitude of each cell in the grid.

The next line contains four integers x_0,y_0,x_f,y_fx\_0, y\_0, x\_f, y\_f (1≤x_0,x_f≤n,1≤y_0,y_f≤m)(1 \leq x\_0, x\_f \leq n, 1 \leq y\_0, y\_f \leq m)—the starting and destination positions.

It is guaranteed that the starting and destination positions are distinct.

출력

Print a single integer—the minimum number of moves required to reach (x_f,y_f)(x\_f, y\_f) from (x_0,y_0)(x\_0, y\_0), or print −1-1 if it is impossible to reach the destination.

예제3

  1. 예제 1

    입력
    4 5
    1 2 3 4 5
    6 7 8 9 10
    11 12 13 14 15
    16 17 18 19 20
    1 1 4 5
    
    예상 출력
    9
    
  2. 예제 2

    입력
    1 4
    1 2 3 1
    1 1 1 4
    
    예상 출력
    -1
    
  3. 예제 3

    입력
    1 2
    1 1
    1 1 1 2
    
    예상 출력
    -1