#2328

Number of Increasing Paths in a Grid

Hard
ArrayDynamic ProgrammingDepth-First SearchBreadth-First SearchGraph TheoryTopological SortMemoizationMatrixDynamic ProgrammingTopological Sorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(m * n * 4^k)
O(m * n * log(m * n))
Space
O(m * n)
O(m * n)
💡

Intuition

Time O(m * n * log(m * n))Space O(m * n)

The optimal solution leverages dynamic programming and topological sorting to efficiently count increasing paths. By processing cells in increasing order, we can build on previously computed results, ensuring we only consider valid increasing paths.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a list of all cells and sort them based on their values.
  2. 2Step 2: Initialize a DP array where dp[i][j] represents the number of increasing paths starting from cell (i, j).
  3. 3Step 3: Iterate through the sorted list of cells, and for each cell, update its adjacent cells if they have a greater value, adding the current cell's path count to the adjacent cell's count.
solution.py14 lines
1def countPaths(grid):
2    mod = 10**9 + 7
3    m, n = len(grid), len(grid[0])
4    cells = [(grid[i][j], i, j) for i in range(m) for j in range(n)]
5    cells.sort()
6    dp = [[1] * n for _ in range(m)]
7    directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
8    total_paths = 0
9    for value, x, y in cells:
10        for dx, dy in directions:
11            nx, ny = x + dx, y + dy
12            if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] > grid[x][y]:
13                dp[nx][ny] = (dp[nx][ny] + dp[x][y]) % mod
14    return sum(sum(row) for row in dp) % mod

Complexity note: The complexity is dominated by the sorting step, which is O(m * n * log(m * n)), followed by a linear pass through the cells to update the DP table.

  • 1Dynamic programming helps avoid recalculating paths for cells already processed.
  • 2Sorting cells by value ensures that we only consider valid increasing paths.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.