Python 1368.py
class Solution:
def minCost(self, grid: List[List[int]]) -> int:
width = len(grid[0])
height = len(grid)
# grid's values => deltas for x and y
signs = { 1: [ +1, 0 ], 2: [ -1, 0 ], 3: [ 0, +1 ], 4: [ 0, -1 ] }
done = {}
todo = [ (0, 0, 0) ] # min-heap cost,x,y
while True:
cost, x, y = heappop(todo)
# already optimized ?
if ( x, y ) in done:
continue
done[( x, y )] = cost
# finish line
if x == width - 1 and y == height - 1:
print(done)
return cost
# process all four directions
for direction in range(1, 4 + 1):
dx, dy = signs[direction]
nx = x + dx
ny = y + dy
if 0 <= nx < width and 0 <= ny < height:
if direction == grid[y][x]:
heappush(todo, ( cost, nx, ny )) # follow the sign
else:
heappush(todo, ( cost + 1, nx, ny )) # modify sign
Difficulty
and has an acceptance rate of about 71% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Breadth First Search
- Graph Theory
- Heap (Priority Queue)
- Matrix
- Shortest Path
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The minCost method computes the smallest number of sign changes required to travel from the top-left corner of a rectangular grid to the bottom-right corner. Each cell contains an integer (1-4) that indicates a preferred movement direction. Moving in the indicated direction incurs no additional cost, while moving in any other direction costs one unit because the sign must be altered. The algorithm explores the grid using a priority queue so that paths with lower accumulated cost are examined first, guaranteeing that the first time the destination cell is reached the cost is minimal.
Key Steps
Initialization
The dimensions of the grid are extracted, a mapping from sign values to coordinate deltas is created, and the data structures for the search are prepared.
width = len(grid[0])
height = len(grid)
signs = { 1: [ +1, 0 ], 2: [ -1, 0 ], 3: [ 0, +1 ], 4: [ 0, -1 ] }
done = {}
todo = [ (0, 0, 0) ] # (cost, x, y) stored in a min-heap
done records the cheapest known cost for each visited cell, while todo holds the frontier of cells to be processed, ordered by their current cost.
Main Loop
The algorithm repeatedly extracts the cell with the lowest accumulated cost from the heap. If the cell has already been settled with a cheaper cost, it is ignored; otherwise its cost is recorded.
while True:
cost, x, y = heappop(todo)
if (x, y) in done:
continue
done[(x, y)] = cost
This loop continues until the destination is reached, ensuring that each cell is processed at most once with its optimal cost.
Termination Check
Immediately after a cell is settled, the algorithm checks whether it is the bottom-right corner. If so, the current cost is the answer and the function returns.
if x == width - 1 and y == height - 1:
print(done)
return cost
The print(done) statement provides a snapshot of the cost map for debugging or inspection.
Neighbor Exploration
For every settled cell, the four possible movement directions are examined. The neighbor coordinates are computed using the signs dictionary, and a bounds check guarantees that only valid grid positions are considered. Depending on whether the movement follows the cell’s original sign, the neighbor is pushed onto the heap with either the same cost or an incremented cost.
for direction in range(1, 4 + 1):
dx, dy = signs[direction]
nx = x + dx
ny = y + dy
if 0 <= nx < width and 0 <= ny < height:
if direction == grid[y][x]:
heappush(todo, (cost, nx, ny)) # no change needed
else:
heappush(todo, (cost + 1, nx, ny)) # sign must be changed
The use of heappush maintains the priority ordering of the frontier.
Edge Cases Handled
The implementation gracefully handles a grid consisting of a single cell. In that scenario the initial heap entry corresponds to the destination, the termination condition is satisfied on the first iteration, and the function returns a cost of zero without entering the neighbor loop.
Out-of-bounds neighbor coordinates are filtered by the explicit range checks 0 <= nx < width and 0 <= ny < height. This prevents attempts to access invalid indices and ensures that the algorithm works correctly for rectangular grids of any size.
When a cell is encountered multiple times through different paths, the done dictionary guarantees that only the first (lowest-cost) occurrence is processed. Subsequent higher-cost arrivals are discarded by the if (x, y) in done: continue guard, preventing unnecessary work and preserving correctness.
If multiple equally cheap routes lead to the same cell, each will be inserted into the heap with the same cost. The first one popped settles the cell, while the others are ignored by the same done check, ensuring deterministic handling of ties without extra overhead.
Performance Optimizations
The algorithm adopts a Dijkstra-style expansion using a min-heap (todo). By always selecting the frontier cell with the smallest accumulated cost, it avoids exploring expensive paths before cheaper ones, which reduces the number of heap operations required to reach the target.
Storing the best known cost for each cell in the done dictionary eliminates revisiting already optimized positions. This memoization prevents the exponential blow-up that a naïve breadth-first search with repeated state expansions would suffer.
The signs dictionary provides constant-time lookup of direction deltas, avoiding conditional branches or repeated calculations for each neighbor.
Early termination upon reaching the destination cell eliminates the need to process the remaining heap entries, which can be substantial in large grids. This cut-off ensures that the algorithm stops as soon as the optimal solution is found.
Overall, the combination of a priority queue, memoization, constant-time direction mapping, and early exit yields an efficient traversal that scales well with grid size while keeping memory usage proportional to the number of cells visited.
ELI5 - Simplified Explanation
Imagine a giant grid on the floor made of colorful square tiles. Each tile has a magic arrow painted on it that points to the north, south, east, or west. You start at the very first square and want to reach the very last one at the bottom corner.
You have a special way of moving across these tiles. If you follow the arrow painted on the square you are standing on, you move for free. It is just like hopping in the direction the arrow says. However, if you decide to go a way that the arrow does not point, you have to pay one gold coin to turn the arrow to match where you want to go.
The computer keeps a list of all the ways you could travel. It always looks for the cheapest path first, which is why it uses a list that stays sorted by the number of gold coins spent. It looks at where you are, checks all four possible directions to move, and figures out if moving that way is free or if it costs a coin.
It keeps track of where it has already been so it does not keep walking in circles. It continues picking the smallest number of gold coins from its list and exploring new squares until it finally reaches the goal at the end of the grid. Once the goal is reached, the computer knows the smallest total amount of coins that make for the quickest trip.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| Shamik07 | Dart | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| Shamik07 | Dart | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ |
Videos
Similar Problems
- problem 2203: Minimum Weighted Subgraph With the Required Paths
Solved On The Same Day
- problem 1400: Construct K Palindrome Strings
- problem 1442: Count Triplets That Can Form Two Arrays of Equal XOR
- problem 1519: Number of Nodes in the Sub-Tree With the Same Label
- problem 1577: Number of Ways Where Square of Number Is Equal to Product of Two Numbers
- problem 1593: Split a String Into the Max Number of Unique Substrings
- problem 1604: Alert Using Same Key-Card Three or More Times in a One Hour Period
- problem 1638: Count Substrings That Differ by One Character
- problem 1695: Maximum Erasure Value
- problem 1726: Tuple with Same Product
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality