Given an H x W grid of integers, return the maximum length of a path where consecutive cells differ by exactly 1 (either increasing or decreasing).
You can move in 4 directions: up, down, left and right. The path must keep one direction of change: either every step increases the value by exactly 1, or every step decreases it by exactly 1. The length of a path is the number of cells on it.
Function Signature
def longest_consecutive_path(grid: list[list[int]]) -> int:
Rules
-
grid
is a list of
H
rows, each of length
W
, and
grid[r][c]
is the value in row
r
, column
c
.
-
A move goes to the cell directly above, below, left or right of the current one. Diagonal moves are not allowed.
-
The direction of change never switches. A path whose values run 3, 4, 5, 4 rises and then falls, so it is not valid.
-
A decreasing path is an increasing path read backward, so both directions give the same answer.
-
Because the values move in one direction, a path never visits a cell twice. A single cell is a path of length 1, so the answer is at least 1.
Constraints
-
1 <= H, W <= 300
-
0 <= grid[i][j] <= 10^5
Examples
Input: grid = [
[1, 2, 3],
[6, 5, 4],
[7, 8, 9]
]
Output: 9
The path 1, 2, 3, 4, 5, 6, 7, 8, 9 runs along the top row, back along the middle row and across the bottom row. Each step adds 1, and the path uses all 9 cells.
Input: grid = [
[1, 2, 3],
[2, 3, 4],
[3, 4, 5]
]
Output: 5
One longest path is 1, 2, 3, 4, 5, which starts in the top-left corner and moves right, down, right, down. Every step that adds 1 here moves right or down, and the values only run from 1 to 5, so no path has more than 5 cells.
Input: grid = [
[3, 4, 5],
[2, 9, 4]
]
Output: 4
The path 2, 3, 4, 5 starts at the bottom-left cell, goes up, then right along the top row. Continuing to the 4 below the 5 would switch from rising to falling, and the 9 differs from each of its neighbors by more than 1, so it cannot join any path.