101 Logo
onenoughtone

Problem Statement

Terrain Navigator

You're a terrain analyst studying elevation data represented as a matrix of integers. Your goal is to find the longest path where the elevation strictly increases as you move.

Given an m x n matrix of integers representing elevations, find the length of the longest increasing path.

From each cell, you can move in four directions: up, down, left, or right. You cannot move diagonally or outside the boundary of the matrix.

The length of a path is the number of cells visited, including the starting cell.

Examples

Example 1:

Input: matrix = [ [9,9,4], [6,6,8], [2,1,1] ]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9], which has a length of 4. Starting from the cell with value 1, you can move to 2, then to 6, and finally to 9.

Example 2:

Input: matrix = [ [3,4,5], [3,2,6], [2,2,1] ]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6], which has a length of 4. Starting from a cell with value 3, you can move to 4, then to 5, and finally to 6.

Example 3:

Input: matrix = [[1]]
Output: 1
Explanation: The matrix has only one cell, so the longest path has a length of 1.

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 200
  • 0 <= matrix[i][j] <= 2^31 - 1

Problem Breakdown

To solve this problem, we need to:

  1. The problem can be modeled as finding the longest path in a directed acyclic graph (DAG)
  2. Each cell is a node, and there's an edge from cell A to cell B if B is adjacent to A and has a higher value
  3. Since we can only move to cells with higher values, there are no cycles in the graph
  4. We can use depth-first search (DFS) with memoization to avoid redundant calculations
  5. The problem has optimal substructure, making it suitable for dynamic programming
  6. We need to try starting the path from each cell in the matrix to find the overall longest path
ProblemSolutionCode
101 Logo
onenoughtone