You are given a grid of positive integers.
The grid is provided as a list of strings, where each string represents one row and the values in that row are separated by commas.
Find the length of the longest valid path in the grid.
You may start from any cell.
From each cell, you may move in 4 directions only: up, down, left, or right.
A path must follow these rules:
- If the path currently has only one cell
A, then the next cell B must satisfy grid[B] ≤ grid[A].
- If the last two cells in the current path are
A then B, then the next cell C must satisfy grid[C] ≤ grid[B] or grid[C] ≤ grid[A].
- You cannot revisit a cell that is already part of the current path.
The length of a path is the number of cells in that path.
Method Signature
int longestConstrainedPath(List<String> grid)
Parameters
grid
- A list of strings representing the rows of the grid.
- Each string contains positive integers separated by commas.
- All rows contain the same number of comma-separated values.
grid.size() = m
- If a row is split by commas, the number of values is
n.
Return Value
Return the maximum number of cells in any valid path.
Constraints
1 ≤ m*n < 20
1 ≤ each grid value ≤ 10^9
- Each row in
grid is a valid comma-separated list of integers.
- All rows must have the same number of values.
Examples
Example 1
Input: grid = ["7"]
Method Call: longestConstrainedPath(grid = ["7"])
Output: 1
Explanation: There is only one cell, so the longest valid path contains that single cell.
Example 2
Input: grid = ["5,4", "3,2"]
Method Call: longestConstrainedPath(grid = ["5,4", "3,2"])
Output: 4
Explanation: One valid path is 5 -> 4 -> 2 -> 3.
4 ≤ 5, then 2 ≤ 4, then 3 ≤ 4.
This path visits all 4 cells, so the answer is 4.
Example 3
Input: grid = ["1,1,1", "2,3,2"]
Method Call: longestConstrainedPath(grid = ["1,1,1", "2,3,2"])
Output: 5
Explanation: One valid path is 3 -> 2 -> 1 -> 1 -> 1.
This path has length 5, and no valid path can visit all 6 cells without revisiting a cell.