#1368

Minimum Cost to Make at Least One Valid Path in a Grid

Hard
ArrayBreadth-First SearchGraph TheoryHeap (Priority Queue)MatrixShortest PathGraph TraversalDijkstra's Algorithm
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution uses a modified Dijkstra's algorithm to find the minimum cost path efficiently. It treats the grid as a graph where each cell connects to its neighbors, and the cost of moving to a neighbor depends on the sign in the current cell.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a priority queue to explore cells based on the cost to reach them, starting from (0, 0) with cost 0.
  2. 2Step 2: Use a 2D array to keep track of the minimum cost to reach each cell, initializing all values to infinity except the starting cell.
  3. 3Step 3: While the priority queue is not empty, extract the cell with the lowest cost, and explore its neighbors. Update the cost to reach each neighbor based on whether the sign points to it or not.
solution.py21 lines
1import heapq
2
3def minCost(grid):
4    m, n = len(grid), len(grid[0])
5    min_cost = [[float('inf')] * n for _ in range(m)]
6    min_cost[0][0] = 0
7    pq = [(0, 0, 0)]  # (cost, x, y)
8    directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
9
10    while pq:
11        cost, x, y = heapq.heappop(pq)
12        if x == m - 1 and y == n - 1:
13            return cost
14        for i in range(4):
15            nx, ny = x + directions[i][0], y + directions[i][1]
16            if 0 <= nx < m and 0 <= ny < n:
17                new_cost = cost + (1 if grid[x][y] != i + 1 else 0)
18                if new_cost < min_cost[nx][ny]:
19                    min_cost[nx][ny] = new_cost
20                    heapq.heappush(pq, (new_cost, nx, ny))
21    return -1

Complexity note: The time complexity is O(n log n) due to the priority queue operations, while the space complexity is O(n) for storing the minimum costs.

  • 1Understanding the grid as a graph helps in visualizing the problem.
  • 2Using a priority queue allows for efficient cost management.

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