#3651

Minimum Cost Path with Teleportations

Hard
ArrayDynamic ProgrammingMatrix
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(m * n * k)
Space
O(1)
O(m * n * k)
💡

Intuition

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

Utilize dynamic programming to systematically calculate the minimum cost to reach each cell, incorporating both normal moves and teleportations. This approach avoids redundant calculations and efficiently tracks costs.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP table with dimensions (m x n x (k + 1)) to store minimum costs.
  2. 2Step 2: Fill the DP table by considering normal moves and teleportations from each cell.
  3. 3Step 3: Return the minimum cost found at the bottom-right cell.
solution.py22 lines
1def minCost(grid, k):
2    from collections import deque
3    m, n = len(grid), len(grid[0])
4    dp = [[[float('inf')] * (k + 1) for _ in range(n)] for _ in range(m)]
5    dp[0][0][0] = 0
6    q = deque([(0, 0, 0)])
7    while q:
8        x, y, t = q.popleft()
9        for dx, dy in [(1, 0), (0, 1)]:
10            nx, ny = x + dx, y + dy
11            if 0 <= nx < m and 0 <= ny < n:
12                cost = dp[x][y][t] + grid[nx][ny]
13                if cost < dp[nx][ny][t]:
14                    dp[nx][ny][t] = cost
15                    q.append((nx, ny, t))
16        if t < k:
17            for i in range(m):
18                for j in range(n):
19                    if grid[i][j] <= grid[x][y] and dp[x][y][t] < dp[i][j][t + 1]:
20                        dp[i][j][t + 1] = dp[x][y][t]
21                        q.append((i, j, t + 1))
22    return min(dp[m - 1][n - 1])

Complexity note: The complexity arises from filling a 3D DP table, where each cell is evaluated for each teleportation count.

  • 1Dynamic programming optimizes the exploration of paths.
  • 2Teleportation allows skipping costly cells, reducing overall cost.

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