find a cost optimized path through a grid/matrix in c
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Finding the minimum-cost path through a grid is a standard optimization problem. In the common version, each cell has a traversal cost, you start at the top-left cell, you want to reach the bottom-right cell, and you may move only right or down.
Dynamic Programming for Right-and-Down Movement
If movement is restricted to right and down, dynamic programming is the right tool. The best cost to reach a cell depends only on the best cost to reach the cell above it and the cell to the left of it.
That gives a simple recurrence:
- cost at start is the value of the start cell
- cost of first row comes only from the left
- cost of first column comes only from above
- every other cell uses the smaller of top and left, plus the current cell cost
Computing the Minimum Cost
The following C++ example computes the minimum total cost:
For the sample grid, the cheapest path is 1 -> 3 -> 1 -> 1 -> 1, for a total cost of 7.
Reconstructing the Path
Sometimes the total cost is not enough; you also need the path itself. To do that, keep a parent direction for each cell while filling the DP table.
This version gives both the optimal cost and the coordinates used to achieve it.
When Dynamic Programming Is Not Enough
The DP approach relies on the restricted move set. If the problem allows movement in four directions, or if some edges are blocked, the grid becomes a shortest-path graph problem. In that case, Dijkstra's algorithm is usually the better choice for non-negative weights.
That distinction matters because many bugs come from applying the right-and-down solution to a problem statement that quietly allows more movement.
Common Pitfalls
Forgetting to include the starting cell cost changes the answer by a constant amount and makes test cases fail unexpectedly.
Using the right-and-down DP approach when the problem allows up or left movement gives incorrect results.
Assuming negative costs are safe can break reasoning about optimal paths. Dynamic programming may still work in the restricted move case, but shortest-path variants need more care.
Skipping path reconstruction details often leads to a correct cost with no usable route output.
Index mistakes in the first row and first column are common because those base cases have only one predecessor.
Summary
- For grids where you can move only right and down, dynamic programming is the standard minimum-cost solution.
- Store cumulative cost in a DP table, then take the smaller predecessor for each cell.
- Add a parent table if you also need the actual path.
- Use Dijkstra instead when the move rules are broader than right and down.
- Handle base cases carefully, especially the first row and first column.

