#K94242. Pathfinding on a Height Grid

    ID: 38598 Type: Default 1000ms 256MiB

Pathfinding on a Height Grid

Pathfinding on a Height Grid

In this problem, you are given a grid of integers where each cell represents the height of the terrain. Your task is to determine if there exists a path from the top-left cell ((0, 0)) to the bottom-right cell ((n-1, m-1)). You can move in four directions (up, down, left, right), but you can only move from one cell to a neighboring cell if the absolute difference in heights does not exceed a given threshold (k). That is, for two adjacent cells at positions ((x, y)) and ((nx, ny)), the condition to move is

[ |grid[nx][ny] - grid[x][y]| \le k ]

Output (YES) if such a path exists, otherwise output (NO).

inputFormat

The first line contains three integers (n), (m), and (k) where (n) and (m) are the number of rows and columns of the grid respectively, and (k) is the maximum allowed height difference between two adjacent cells. This is followed by (n) lines, each containing (m) integers representing the grid.

outputFormat

Output a single line containing either (YES) if there exists a valid path from the top-left to the bottom-right of the grid, or (NO) otherwise.## sample

3 3 1
1 2 3
2 3 4
3 4 5
YES