#1301
Number of Paths with Max Score
HardArrayDynamic ProgrammingMatrixDynamic ProgrammingGrid Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n²) |
💡
Intuition
Time O(n²)Space O(n²)
The optimal approach uses dynamic programming to efficiently calculate the maximum score and the number of paths to reach 'E'. We maintain two DP tables: one for scores and another for path counts, updating them based on previously computed values.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two DP tables: one for maximum scores and another for path counts, both of the same size as the board.
- 2Step 2: Start filling the DP tables from the bottom-right corner (S) and move towards the top-left corner (E).
- 3Step 3: For each cell, if it's not an obstacle, update the score and path count based on valid moves from below, left, and diagonally.
- 4Step 4: Return the maximum score and the number of paths that lead to that score from the top-left corner.
solution.py29 lines
1def maxScorePaths(board):
2 MOD = 10**9 + 7
3 n = len(board)
4 dp_score = [[0] * n for _ in range(n)]
5 dp_count = [[0] * n for _ in range(n)]
6 dp_count[n - 1][n - 1] = 1 # Start from 'S'
7
8 for i in range(n - 1, -1, -1):
9 for j in range(n - 1, -1, -1):
10 if board[i][j] == 'X':
11 continue
12 if i == n - 1 and j == n - 1:
13 continue
14 max_score = 0
15 if i + 1 < n:
16 max_score = max(max_score, dp_score[i + 1][j])
17 if j + 1 < n:
18 max_score = max(max_score, dp_score[i][j + 1])
19 if i + 1 < n and j + 1 < n:
20 max_score = max(max_score, dp_score[i + 1][j + 1])
21 dp_score[i][j] = max_score + (int(board[i][j]) if board[i][j].isdigit() else 0)
22 if max_score == dp_score[i + 1][j]:
23 dp_count[i][j] += dp_count[i + 1][j]
24 if max_score == dp_score[i][j + 1]:
25 dp_count[i][j] += dp_count[i][j + 1]
26 if max_score == dp_score[i + 1][j + 1]:
27 dp_count[i][j] += dp_count[i + 1][j + 1]
28
29 return [dp_score[0][0], dp_count[0][0] % MOD] if dp_score[0][0] > 0 else [0, 0]ℹ
Complexity note: Both time and space complexities are O(n²) because we are using two 2D arrays (DP tables) to store scores and path counts for each cell in the n x n board.
- 1Dynamic programming is essential for optimizing pathfinding problems.
- 2Tracking both scores and counts can help solve complex path problems efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.