{"id":"minimum-path-cost-in-a-grid","title":"Minimum Path Cost in a Grid","difficulty":"medium","patterns":["dp-2d"],"primaryConcept":"dp-2d-grid","concepts":["dp-2d-grid"],"problemForm":"core","companies":["Google","Amazon","Microsoft"],"category":"dynamic-programming","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"grid-move-cost","primaryParam":"grid","secondaryParam":"moveCost","sizeMetric":"matrix-cells","sizes":[4,6,12,25]},"description":"You are given a matrix `grid` of distinct values and a matrix `moveCost`. You may start at any cell in the first row. From a cell `grid[row][col]`, you may move to any cell in the next row, and the move cost is `moveCost[grid[row][col]][nextCol]`.\n\nThe total path cost is the sum of all visited grid values plus all move costs. Return the minimum total cost of any path from the first row to the last row.","examples":[{"input":"grid = [[5,3],[4,0],[2,1]], moveCost = [[9,8],[1,5],[10,12],[18,6],[2,4],[14,3]]","output":"17","explanation":"One cheapest path is 5 -> 0 -> 1 with move costs 3 and 8, for total 5 + 3 + 0 + 8 + 1 = 17."},{"input":"grid = [[5,1,2],[4,0,3]], moveCost = [[12,10,15],[20,23,8],[21,7,1],[8,1,13],[9,10,25],[5,3,2]]","output":"6","explanation":"Start at value 2 and move to value 3 with transition cost 1, giving 2 + 1 + 3 = 6."},{"input":"grid = [[0,1],[2,3]], moveCost = [[1,2],[3,4],[5,6],[7,8]]","output":"3","explanation":"Start at 0, move to 2, and pay moveCost[0][0] = 1 for total 0 + 1 + 2 = 3."}],"constraints":[{"id":"m-len-grid","text":"m == len(grid)"},{"id":"n-len-grid-i","text":"n == len(grid[i])"},{"id":"2-m-n-50","text":"2 <= m, n <= 50","check":[{"kind":"sizeRange","target":"grid","measure":"matrixRows","min":2,"max":50},{"kind":"valueRange","target":"grid","selector":"arrayItemLengths","min":2,"max":50}]},{"id":"grid-contains-distinct-integers-from-0-to-m-n-1","text":"grid contains distinct integers from 0 to m * n - 1"},{"id":"movecost-length-m-n","text":"len(moveCost) == m * n"},{"id":"movecost-i-length-n","text":"len(moveCost[i]) == n"},{"id":"1-movecost-i-j-100","text":"1 <= moveCost[i][j] <= 100","check":{"kind":"valueRange","target":"moveCost","selector":"nestedArrayItems","min":1,"max":100}}],"starterCode":"class Solution:\n    def minPathCost(self, grid: list[list[int]], moveCost: list[list[int]]) -> int:\n        # Your code here\n        pass","functionName":"minPathCost","testCases":[{"id":"1","input":{"grid":[[5,3],[4,0],[2,1]],"moveCost":[[9,8],[1,5],[10,12],[18,6],[2,4],[14,3]]},"expected":17,"description":"Canonical three-row example."},{"id":"2","input":{"grid":[[5,1,2],[4,0,3]],"moveCost":[[12,10,15],[20,23,8],[21,7,1],[8,1,13],[9,10,25],[5,3,2]]},"expected":6,"description":"Two rows with best path starting from the last first-row cell."},{"id":"3","input":{"grid":[[0,1],[2,3]],"moveCost":[[1,2],[3,4],[5,6],[7,8]]},"expected":3,"description":"Small custom grid."},{"id":"h3","input":{"grid":[[1,0,2],[3,4,5],[6,7,8]],"moveCost":[[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15],[16,17,18],[19,20,21],[22,23,24],[25,26,27]]},"expected":20,"description":"Three-column validation case."},{"id":"h4","input":{"grid":[[0,2],[1,3],[4,5]],"moveCost":[[2,9],[8,1],[4,3],[7,6],[5,5],[5,5]]},"expected":9,"description":"Best path switches columns across three rows."},{"id":"h1","input":{"grid":[[2,1],[3,0]],"moveCost":[[1,1],[1,1],[1,1],[1,1]]},"expected":2,"description":"Uniform move costs still favor the smallest reachable end cell."},{"id":"h2","input":{"grid":[[1,2,3],[4,5,6]],"moveCost":[[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]]},"expected":6,"description":"Uniform move costs still favor the smallest total start and end values."},{"id":"h5","input":{"grid":[[4,1],[3,2],[6,5]],"moveCost":[[1,1],[1,1],[1,1],[1,1],[1,1],[1,1],[1,1]]},"expected":10,"description":"Three rows with uniform move costs reduce to the smallest row values plus transitions."},{"id":"h6","input":{"grid":[[0,2],[1,3]],"moveCost":[[5,9],[4,1],[7,2],[3,6]]},"expected":6,"description":"Nonzero transition costs can outweigh a larger destination value."},{"id":"h7","input":{"grid":[[5,2,6],[4,3,1],[7,8,0]],"moveCost":[[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]]},"expected":5,"description":"Uniform transition costs add one move cost per row transition."},{"id":"topup-two-row-choice","input":{"grid":[[0,1,2],[3,4,5]],"moveCost":[[5,1,9],[2,8,2],[6,1,1],[1,1,1],[1,1,1],[1,1,1]]},"expected":5,"description":"Two-row grid chooses the cheapest transition column."},{"id":"topup-three-row-detour","input":{"grid":[[0,2],[1,3],[4,5]],"moveCost":[[3,8],[2,2],[1,7],[6,1],[1,1],[1,1]]},"expected":10,"description":"Three rows require carrying the best prior column cost."},{"id":"cheapest-move-skips-a-column","input":{"grid":[[0,1,2],[3,4,5]],"moveCost":[[100,100,1],[100,100,100],[100,100,100],[100,100,100],[100,100,100],[100,100,100]]},"expected":6,"description":"The cheapest move goes from column 0 to column 2, two columns over."}],"hints":[{"level":1,"content":"The best cost to reach a cell in the current row depends on every cell in the previous row.","revealPattern":false},{"level":2,"content":"Keep one DP array for the previous row and build a new one for the current row.","revealPattern":true},{"level":3,"content":"For each current column, try all previous columns and add moveCost[previous_value][current_column].","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"rolling-row-dp","name":"Rolling row DP","summary":"Keep previous-row costs, compute each current-row column by trying all previous columns, then replace the row.","decisionReason":"prev[col] holds the cheapest cost to finish at each column of the previous row. To fill one current cell, every previous column contributes prev[pc] + moveCost[grid[row-1][pc]][col] + grid[row][col], so only one row of state has to survive.","complexity":{"time":"O(m * n^2)","space":"O(n)"},"tradeoffs":["Runs in O(m * n^2) time and uses O(n) space."],"isOptimal":true},{"id":"enumerate-paths","name":"Enumerate paths","summary":"Try every possible column choice in every row.","decisionReason":"Each row multiplies the route count by n, so enumeration re-walks exponentially many route suffixes that share the same cells, which is exactly the repeated work the rolling DP collapses.","complexity":{"time":"O(n^m)","space":"O(m)"},"tradeoffs":["Runs in O(n^m) time and uses O(m) space."],"isOptimal":false},{"id":"local-cheapest","name":"Choose cheapest next move","summary":"At each row, pick the immediate cheapest move cost.","decisionReason":"A cheap immediate move can land on a value whose later outgoing transitions are expensive, because the next move cost depends on the value you leave.","complexity":{"time":"O(m*n)","space":"O(1)"},"tradeoffs":["Runs in O(m*n) time and uses O(1) space."],"isOptimal":false}]},"codingCheckpoints":[{"id":"init-first-row","title":"Seed first-row costs","description":"Initialize the rolling DP state from every value in the first row.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_recurrence_state","scope":"init-rolling-states","readMode":"dp-value-query-v1"}]},"commonMistakes":["Starting only from the first column","Initializing all DP costs to zero"],"hint":"Copy grid[0] into the initial DP array."},{"id":"init-current-row","title":"Create current-row state","description":"For each row after the first, allocate a fresh state array for that row's best costs.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_sentinel_indexed_state_store","scope":"init-dp","readMode":"dp-value-query-v1"}]},"commonMistakes":["Updating the previous row in place before all transitions are read","Reusing stale current-row values"],"hint":"Create a new array of length n inside the row loop."},{"id":"scan-rows","title":"Scan rows after the first","description":"Process each row from top to bottom, starting at row 1.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_indexed_state_space","scope":"outer-loop","readMode":"dp-value-query-v1"}]},"commonMistakes":["Skipping the last row","Starting at row 0 and double-counting first-row values"],"hint":"Loop row from 1 to m - 1."},{"id":"scan-previous-columns","title":"Try all previous columns","description":"For each current column, inspect every previous-row column as a candidate predecessor.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_nested_choice_state_space","scope":"inner-loop","readMode":"dp-value-query-v1"}]},"commonMistakes":["Only checking the same column","Only checking adjacent columns"],"hint":"Nest a previous-column loop inside the current-column loop."},{"id":"compute-transition","title":"Compute transition cost","description":"Combine the previous DP cost with the move cost based on the previous cell value and current column.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"computes_recurrence_transition","scope":"compute-next-states","readMode":"dp-value-query-v1"}]},"commonMistakes":["Indexing moveCost by the previous column instead of previous cell value","Forgetting to include the previous DP cost"],"hint":"candidate = dp[prev_col] + moveCost[grid[row - 1][prev_col]][col]."},{"id":"write-current-cost","title":"Write the best current cost","description":"Store the current grid value plus the best predecessor cost, then roll the row forward.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"writes_recurrence_state","scope":"keep-better-outcome","readMode":"dp-value-query-v1"}]},"commonMistakes":["Storing only the move cost","Forgetting to replace dp with the current row"],"hint":"current[col] = grid[row][col] + best, then assign dp = current after the row."},{"id":"return-minimum-last-row","title":"Return the best last-row cost","description":"After processing all rows, return the minimum value in the final DP row.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_indexed_terminal_state","scope":"return-result","readMode":"dp-value-query-v1"}]},"commonMistakes":["Returning a specific last column","Returning the whole DP array"],"hint":"Use min(dp)."}],"complexityAnalysis":{"time":{"complexity":"O(m * n^2)","explanation":"For each row and current column, every previous column is considered."},"space":{"complexity":"O(n)","explanation":"Only the previous and current row of DP costs are stored."}},"slides":[{"id":"read-the-signal","kind":"info","chapter":"The grid","eyebrow":"Read the problem","title":"Cheapest way down the grid","workspacePanel":"problem","body":["You walk from the top row to the bottom row of a grid, one cell per row. From a cell you may step to any column in the next row, and each step charges a move cost that depends on the value you are leaving and the column you land on. The total is every grid value you stand on plus every move cost you pay.","Many routes can reach the same cell. Only the cheapest cost into each cell matters before the next row adds its grid value and move cost."]},{"id":"enumerate","kind":"code-trace","chapter":"The obvious way","eyebrow":"The obvious way","title":"Follow every column choice","summary":"Trying every column choice in every row gets the right total, but each row branches into a fresh set of routes. Watch how fast the number of routes grows.","workspacePanel":"trace","body":["From a cell the routine tries stepping to every column of the next row, recurses on each, and keeps the cheapest continuation."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def minPathCost(grid: list[list[int]], moveCost: list[list[int]]) -> int:\n    m = len(grid)\n    n = len(grid[0])\n    def best(row: int, col: int) -> int:\n        if row == m - 1:\n            return grid[row][col]\n        cheapest = moveCost[grid[row][col]][0] + best(row + 1, 0)\n        for nxt in range(1, n):\n            cand = moveCost[grid[row][col]][nxt] + best(row + 1, nxt)\n            if cand < cheapest:\n                cheapest = cand\n        return grid[row][col] + cheapest\n    return min(best(0, start) for start in range(n))","steps":[{"id":"branch-from-5","title":"Pick a first-row start, then branch to every next column","codeLine":13,"summary":"The outer call tries every first-row start; best(0,0) on value 5 then steps into column 0 and column 1 of the next row, opening one subtree per choice.","state":{"grid":[[5,3],[4,0],[2,1]],"nums":[5,3],"labels":{"nums":"top row","grid":"grid","r":"row","c":"col"},"r":0,"c":0}},{"id":"descend-first","title":"Follow the first choice down","codeLine":9,"summary":"The column-0 branch calls best(1,0) on value 4, which will itself fan out to every column of the last row.","state":{"grid":[[5,3],[4,0],[2,1]],"nums":[5,3],"labels":{"nums":"top row","grid":"grid","r":"row","c":"col"},"r":1,"c":0}},{"id":"bottom-out","title":"A route bottoms out at the last row","codeLine":6,"summary":"best(2,1) reaches the last row and returns its own value, 1, the end of one complete route.","state":{"grid":[[5,3],[4,0],[2,1]],"nums":[5,3],"labels":{"nums":"top row","grid":"grid","r":"row","c":"col"},"r":2,"c":1}},{"id":"resolve-other","title":"The same cell's second choice is a whole new subtree","codeLine":9,"summary":"Back at best(1,0), the column-1 branch calls best(2,1) all over again, a second full descent that overlaps the first.","state":{"grid":[[5,3],[4,0],[2,1]],"nums":[5,3],"labels":{"nums":"top row","grid":"grid","r":"row","c":"col"},"r":1,"c":1}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const m = grid.length;\nconst n = grid[0].length;\nfunction best(row, col) {\n    if (row === (m - 1)) {\n        return grid[row][col];\n    }\n    let cheapest = moveCost[grid[row][col]][0] + best((row + 1), 0);\n    for (let nxt = 1; nxt < n; nxt++) {\n        const cand = moveCost[grid[row][col]][nxt] + best((row + 1), nxt);\n        if (cand < cheapest) {\n            cheapest = cand;\n        }\n    }\n    return (grid[row][col] + cheapest);\n}\nconst result = Math.min(...Array.from({ length: n }, (_, index) => index).map((start) => best(0, start)));\nreturn result;","lineMap":{"2":1,"3":2,"5":4,"6":5,"7":7,"8":8,"9":9,"10":10,"11":11,"12":14,"13":16},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":5,"endLine":6},"11":{"startLine":11,"endLine":13},"12":{"startLine":14,"endLine":15},"13":{"startLine":16,"endLine":17}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const m = grid.length;\nconst n = grid[0].length;\nfunction best(row: number, col: number): number {\n    if (row === (m - 1)) {\n        return grid[row][col];\n    }\n    let cheapest = moveCost[grid[row][col]][0] + best((row + 1), 0);\n    for (let nxt = 1; nxt < n; nxt++) {\n        const cand = moveCost[grid[row][col]][nxt] + best((row + 1), nxt);\n        if (cand < cheapest) {\n            cheapest = cand;\n        }\n    }\n    return (grid[row][col] + cheapest);\n}\nconst result = Math.min(...Array.from({ length: n }, (_, index) => index).map((start) => best(0, start)));\nreturn result;","lineMap":{"2":1,"3":2,"5":4,"6":5,"7":7,"8":8,"9":9,"10":10,"11":11,"12":14,"13":16},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":5,"endLine":6},"11":{"startLine":11,"endLine":13},"12":{"startLine":14,"endLine":15},"13":{"startLine":16,"endLine":17}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int m = grid.Count;\nint n = grid[0].Count;\nint Best(int row, int col) {\n    if (row == m - 1) {\n        return grid[row][col];\n    }\n    int cheapest = moveCost[grid[row][col]][0] + Best(row + 1, 0);\n    for (int nxt = 1; nxt < n; nxt++) {\n        int cand = moveCost[grid[row][col]][nxt] + Best(row + 1, nxt);\n        if (cand < cheapest) {\n            cheapest = cand;\n        }\n    }\n    return grid[row][col] + cheapest;\n    return 0;\n}\nint result = Enumerable.Range(0, n).Select(start => Best(0, start)).ToList().Min();\nreturn result;","lineMap":{"2":1,"3":2,"5":4,"6":5,"7":7,"8":8,"9":9,"10":10,"11":11,"12":14,"13":17},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":5,"endLine":6},"11":{"startLine":11,"endLine":13},"12":{"startLine":14,"endLine":16},"13":{"startLine":17,"endLine":18}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<int(int, int)> best;\n\nint m = grid.size();\nint n = grid[0].size();\nbest = [&]( int row, int col ) -> int {\n    if (row == (m - 1)) {\n        return grid[row][col];\n    }\n    int cheapest = move_cost[grid[row][col]][0] + best((row + 1), 0);\n    for (int nxt = 1; nxt < n; nxt++) {\n        int cand = move_cost[grid[row][col]][nxt] + best((row + 1), nxt);\n        if (cand < cheapest) {\n            cheapest = cand;\n        }\n    }\n    return (grid[row][col] + cheapest);\n};\nint result = int{};\nbool has_value = false;\nfor (int start = 0; start < n; start++) {\n    int candidate = best(0, start);\n    if (!has_value || candidate < result) {\n        result = candidate;\n        has_value = true;\n    }\n}\nreturn result;","lineMap":{"2":3,"3":4,"5":6,"6":7,"7":9,"8":10,"9":11,"10":12,"11":13,"12":16,"13":18},"statementBundles":{"3":{"startLine":4,"endLine":5},"6":{"startLine":7,"endLine":8},"11":{"startLine":13,"endLine":15},"12":{"startLine":16,"endLine":17},"13":{"startLine":18,"endLine":27}},"alternateStyles":{"close-to-source":{"code":"function<int(int, int)> best;\n\nint m = grid.size();\nint n = grid[0].size();\nbest = [&]( int row, int col ) -> int {\n    if (row == (m - 1)) {\n        return grid[row][col];\n    }\n    int cheapest = move_cost[grid[row][col]][0] + best((row + 1), 0);\n    for (int nxt = 1; nxt < n; nxt++) {\n        int cand = move_cost[grid[row][col]][nxt] + best((row + 1), nxt);\n        if (cand < cheapest) {\n            cheapest = cand;\n        }\n    }\n    return (grid[row][col] + cheapest);\n};\nint result = ([&] { int best_value = int{}; bool has_value = false; for (int start = 0; start < n; start++) { auto current_value = best(0, start); if (!has_value || current_value < best_value) { best_value = current_value; has_value = true; } } return best_value; }());\nreturn result;","lineMap":{"2":3,"3":4,"5":6,"6":7,"7":9,"8":10,"9":11,"10":12,"11":13,"12":16,"13":18},"statementBundles":{"3":{"startLine":4,"endLine":5},"6":{"startLine":7,"endLine":8},"11":{"startLine":13,"endLine":15},"12":{"startLine":16,"endLine":17},"13":{"startLine":18,"endLine":19}}}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static int best(int row, int col, int m, List<List<Integer>> grid, List<List<Integer>> moveCost, int n) {\n    if (row == (m - 1)) {\n        return grid.get(row).get(col);\n    }\n    int cheapest = moveCost.get(grid.get(row).get(col)).get(0) + best((row + 1), 0, m, grid, moveCost, n);\n    for (int nxt = 1; nxt < n; nxt++) {\n        int cand = moveCost.get(grid.get(row).get(col)).get(nxt) + best((row + 1), nxt, m, grid, moveCost, n);\n        if (cand < cheapest) {\n            cheapest = cand;\n        }\n    }\n    return (grid.get(row).get(col) + cheapest);\n}\n\nint m = grid.size();\nint n = grid.get(0).size();\nint result = java.util.stream.IntStream.range(0, n).boxed().mapToInt(start -> best(0, start, m, grid, moveCost, n)).min().orElseThrow();\nreturn result;","lineMap":{"2":15,"3":16,"5":2,"6":3,"7":5,"8":6,"9":7,"10":8,"11":9,"12":12,"13":17},"statementBundles":{"6":{"startLine":3,"endLine":4},"11":{"startLine":9,"endLine":11},"12":{"startLine":12,"endLine":13},"13":{"startLine":17,"endLine":18}}}}}},{"id":"enumerate-cost","kind":"case-probe","chapter":"The obvious way","eyebrow":"Count the routes","title":"How many full routes does a grid of m rows and n columns have?","workspacePanel":"visualizer","summary":"Each row offers a free choice of any of the n columns, independent of the rows before it.","options":[{"id":"exponential","label":"n to the power m, one per sequence of column choices","rationale":"Every row multiplies the count by n choices, so a 5 by 5 grid already has 5^5 = 3125 distinct routes and it explodes from there. Walking each one in full is the cost.","isCorrect":true},{"id":"linear","label":"m times n, one per cell","rationale":"That counts cells, not routes. A single cell sits on countless routes, and the recursion re-solves it once per route that passes through."},{"id":"squared","label":"n squared, the columns paired up","rationale":"Pairing columns counts one transition, but a route chains a fresh column choice in every row, so the count compounds across all m rows."}],"answer":"n to the power m. Each row multiplies the choices, so the route count grows exponentially with the number of rows, and re-walking each full route is what makes the naive solution unusable.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"route-count","summary":"Each row branches into n column choices, so the routes multiply row by row: for this 3-row, 2-column grid the choices fan out to 2 x 2 x 2 = 8 leaf routes.","state":{"tree":["start","col 0","col 1","col 0","col 1","col 0","col 1","route","route","route","route","route","route","route","route"]}}]}},{"id":"where-from","kind":"case-probe","chapter":"The idea","eyebrow":"Find the structure","title":"To stand on a cell, where could the previous step have come from?","workspacePanel":"visualizer","summary":"A step moves from a cell to any column in the very next row.","options":[{"id":"any-prev-col","label":"Any column of the row directly above","rationale":"A move crosses from some cell in the previous row to this one, and it may land on any column, so every previous-row column is a possible source.","isCorrect":true},{"id":"same-col","label":"Only the cell directly above, same column","rationale":"Moves are not restricted to the same column. A step may cross from any column of the previous row to this one."},{"id":"adjacent","label":"Only the columns next to it, like a diagonal step","rationale":"There is no adjacency limit. The move cost is defined for every previous value and every landing column, so any column above can reach this cell."}],"answer":"From any column of the row above. A single move may cross to any column, so to reach this cell the previous step could have left from any cell in the previous row.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"where-state","state":{"grid":[[5,3],[4,0],[2,1]],"nums":[5,3],"labels":{"nums":"top row","grid":"grid","r":"row","c":"col"},"r":1,"c":0,"filled":[[0,0],[0,1]],"changed":[]}}]}},{"id":"carry-what","kind":"case-probe","chapter":"The idea","eyebrow":"Find what is enough","title":"What is enough to remember about a row before moving on?","workspacePanel":"visualizer","summary":"The naive trace reaches the same row cells through many different partial routes, re-walking shared work again and again.","options":[{"id":"cheapest-per-col","label":"The cheapest total to reach each column of that row, one number per column","rationale":"Any later step that arrives from a column only needs the cheapest way to have reached it, so one best cost per column captures everything the next row will ask for. Call this rolling array dp.","isCorrect":true},{"id":"every-route","label":"Every full route that reaches the row","rationale":"Keeping whole routes is exactly the exponential cost the naive solution paid. The next row only ever asks how cheaply each column was reached, not by which path."},{"id":"single-best","label":"Just the single cheapest cell in the row","rationale":"The next column might be reached most cheaply from a column that was not the row's overall cheapest, so one number for the whole row throws away choices you still need."}],"answer":"The cheapest total to reach each column, one number per column. Keep that rolling array, called dp, and the next row can be built from it without ever looking at full routes.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"carry-state","state":{"grid":[[5,3],[4,0],[2,1]],"nums":[5,3],"labels":{"nums":"dp","grid":"grid","r":"row","c":"col"},"i":0}}]}},{"id":"transition-rule","kind":"case-probe","chapter":"The idea","eyebrow":"Find the rule","title":"The cheapest way onto a cell is its value plus what?","workspacePanel":"visualizer","summary":"We are filling row 1, column 0. Its grid value is 4, and the previous row contains values 5 and 3.","options":[{"id":"best-source","label":"The cheapest (dp at a previous column plus the move cost from it) across all previous columns","rationale":"Each previous column offers an arrival cost of dp[prev] plus the move cost charged for leaving its value, and the cheapest of those, added to this cell's value, is the best way onto it.","isCorrect":true},{"id":"cheapest-dp-only","label":"The smallest dp value in the previous row","rationale":"The cheapest column to have reached is not always the cheapest to step from, because the move cost depends on which value you leave and which column you land on."},{"id":"move-only","label":"The smallest move cost into this column","rationale":"A tiny move cost from an expensive-to-reach column can lose to a larger move from a cheaply reached one, so the stored dp cost has to be added before comparing."}],"answer":"Plus the cheapest arrival. For this cell, take the minimum over previous columns of dp[prev] + moveCost[previous value][this column], then add the cell's own grid value.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"rule-state","state":{"grid":[[5,3],[4,0],[2,1]],"nums":[5,3],"labels":{"nums":"dp","grid":"grid","r":"row","c":"col"},"r":1,"c":0,"i":0,"filled":[[0,0],[0,1]],"changed":[]}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which approach should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"grid":[[5,3],[4,0],[2,1]],"nums":[5,3],"labels":{"nums":"dp","grid":"grid","r":"row","c":"col"}}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"Seed the first row, then roll downward","workspacePanel":"visualizer","body":["dp starts as the first row itself: the cheapest way onto each top cell is simply its own value, so dp is 5 then 3.","For each row below, every column takes its grid value plus the cheapest dp[prev] + moveCost[previous value][this column] over all previous columns, and the finished row becomes the new dp."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"seed-state","state":{"grid":[[5,3],[4,0],[2,1]],"nums":[5,3],"labels":{"nums":"dp","grid":"grid","r":"row","c":"col"},"i":0}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Roll the row","title":"Roll dp down the grid","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"row1-col0","state":{"grid":[[5,3],[4,0],[2,1]],"nums":[5,3],"labels":{"nums":"dp","grid":"grid","r":"row","c":"col"},"r":1,"c":0,"i":0,"filled":[[0,0],[0,1]],"changed":[]}},{"id":"row1-col1","state":{"grid":[[5,3],[4,0],[2,1]],"nums":[23,3],"labels":{"nums":"dp","grid":"grid","r":"row","c":"col"},"r":1,"c":1,"i":1,"filled":[[0,0],[0,1]],"changed":[]}},{"id":"row2-col1","state":{"grid":[[5,3],[4,0],[2,1]],"nums":[23,8],"labels":{"nums":"dp","grid":"grid","r":"row","c":"col"},"r":2,"c":1,"i":1,"filled":[[1,0],[1,1]],"changed":[]}}]},"beats":[{"id":"row1-col0","title":"Row 1, column 0 holds value 4. What is its cheapest arrival?","summary":"dp is 5, 3. From column 0 (value 5) the move into column 0 costs moveCost[5][0] = 14; from column 1 (value 3) it costs moveCost[3][0] = 18.","prompt":"Both previous columns are filled in dp.","options":[{"id":"c23","label":"23 = 4 + min(5 + 14, 3 + 18)","rationale":"Arriving from column 0 costs 5 + 14 = 19, from column 1 costs 3 + 18 = 21, so the cheaper is 19 and 4 + 19 = 23.","isCorrect":true},{"id":"c21","label":"21 = 4 + min(5, 3) + something","rationale":"Comparing the raw dp values alone ignores the move cost, which differs per source column and changes which arrival is actually cheaper."},{"id":"c8","label":"8 = 4 + min(14, 18)","rationale":"That drops the dp cost of reaching each previous column. The arrival cost includes dp[prev] as well as the move."}],"answer":"23. The cheaper arrival is from column 0 at 5 + 14 = 19, so 4 + 19 = 23."},{"id":"row1-col1","title":"Row 1, column 1 holds value 0. Which source wins here?","summary":"From column 0 (value 5) the move into column 1 costs moveCost[5][1] = 3; from column 1 (value 3) it costs moveCost[3][1] = 6.","prompt":"The two move costs differ from the last cell.","options":[{"id":"from0","label":"Column 0, for 8 = 0 + min(5 + 3, 3 + 6)","rationale":"Column 0 arrives at 5 + 3 = 8, column 1 at 3 + 6 = 9, so column 0 wins and 0 + 8 = 8. The winning source is not the same as last time.","isCorrect":true},{"id":"from1","label":"Column 1, for 9 = 0 + (3 + 6)","rationale":"Column 1 arrives at 9, which is more than column 0's 8, so column 0 is the cheaper source into this cell."},{"id":"zero","label":"0, its own value","rationale":"A cell must include the cheapest cost of getting onto it, not only its own grid value."}],"answer":"Column 0 arrives cheapest at 5 + 3 = 8, so 0 + 8 = 8; dp becomes [23, 8]."},{"id":"row2-col1","title":"Row 2, column 1 holds value 1. What is the cheapest total here?","summary":"dp is now 23, 8. The previous row's values are 4 at column 0 and 0 at column 1, so a step into column 1 costs moveCost[4][1] = 4 or moveCost[0][1] = 8.","prompt":"This is the last row, so this cell is a possible finish.","options":[{"id":"c17","label":"17 = 1 + min(23 + 4, 8 + 8)","rationale":"Arriving from column 0 costs 23 + 4 = 27, from column 1 costs 8 + 8 = 16, so the cheaper is 16 and 1 + 16 = 17.","isCorrect":true},{"id":"c27","label":"27 = 1 + (23 + 4)","rationale":"That takes the column-0 source at 27, but column 1 arrives more cheaply at 16, so it is not the minimum."},{"id":"c9","label":"9 = 1 + 8","rationale":"That uses dp at column 1 but forgets the move cost moveCost[0][1] = 8 charged for the step itself."}],"answer":"17. Column 1 arrives cheapest at 8 + 8 = 16, so 1 + 16 = 17, the cheapest finish in the bottom row."}]},{"id":"value-vs-column-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","workspacePanel":"trace","title":"Could the move cost be keyed by the previous column?","summary":"prev_col is already in hand, and the table still fills cleanly from top to bottom, so keying the move cost by it reads like a tidy shortcut. The first row where a column index and the value standing in it diverge will show whether that shortcut is legitimate.","pitfall":"The loop below keys the move cost by prev_col, the column index, instead of by grid[row - 1][prev_col], the value standing in that column.","whyItMatters":"Column 1 of the first row holds value 3, whose real transition row is moveCost[3] = [18, 6], but moveCost[1] = [1, 5] is far cheaper, so the table invents bargain moves. On grid [[5,3],[4,0],[2,1]] the corner lands at 11, below the true answer of 17 and below any real path. Key the move cost by the previous cell's value, not its column.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"m = len(grid)\nn = len(grid[0])\ndp = [[0] * n for _ in range(m)]\nfor col in range(n):\n    dp[0][col] = grid[0][col]\nfor row in range(1, m):\n    for col in range(n):\n        best = dp[0][0]\n        first = True\n        for prev_col in range(n):\n            prev = dp[row - 1][prev_col]\n            step = moveCost[prev_col][col]\n            total = prev + step\n            if first or total < best:\n                best = total\n                first = False\n        dp[row][col] = grid[row][col] + best\nout = dp[m - 1][0]\nfor col in range(n):\n    val = dp[m - 1][col]\n    if val < out:\n        out = val\nreturn out","steps":[{"id":"seed","title":"The top row of dp seeds from the grid","codeLine":5,"summary":"dp[0] becomes 5, 3, the cost to land on each first-row cell.","state":{"grid":[[5,3],[0,0],[0,0]],"r":0,"c":1,"filled":[[0,0],[0,1]],"labels":{"grid":"dp","r":"row","c":"col"},"changed":[]}},{"id":"wrong-key-col0","title":"Column 0 keys the move by column index","codeLine":12,"summary":"For value 4, the step from column 1 reads moveCost[1][0] = 1 instead of moveCost[3][0] = 18, since value 3 sits in column 1. So total = 3 + 1 = 4 looks like a bargain and dp[1][0] = 4 + 4 = 8 instead of 23.","state":{"grid":[[5,3],[8,0],[0,0]],"r":1,"c":0,"filled":[[0,0],[0,1],[1,0]],"labels":{"grid":"dp","r":"row","c":"col"},"changed":[]}},{"id":"wrong-key-col1","title":"The same wrong key cheapens column 1","codeLine":12,"summary":"For value 0, the step from column 1 reads moveCost[1][1] = 5 instead of moveCost[3][1] = 6, and dp[1][1] = 0 + min(9 + 5, 3 + 5) = 8. The whole row is built from moves that were never charged.","state":{"grid":[[5,3],[8,8],[0,0]],"r":1,"c":1,"filled":[[0,0],[0,1],[1,0],[1,1]],"labels":{"grid":"dp","r":"row","c":"col"},"changed":[]}},{"id":"impossible","title":"The bottom row lands at 11, below any real path","codeLine":17,"summary":"dp[2] fills to 11, 14 and min(dp[2]) returns 11. No route through this grid can cost less than 17. Keying by column invented cheaper moves that do not exist.","state":{"grid":[[5,3],[8,8],[11,14]],"r":2,"c":0,"filled":[[0,0],[0,1],[1,0],[1,1],[2,0],[2,1]],"labels":{"grid":"dp","r":"row","c":"col"},"changed":[]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const m = grid.length;\nconst n = grid[0].length;\nconst dp = Array.from({ length: m }, () => Array(n).fill(0));\nfor (let col = 0; col < n; col++) {\n    dp[0][col] = grid[0][col];\n}\nfor (let row = 1; row < m; row++) {\n    for (let col = 0; col < n; col++) {\n        let best = dp[0][0];\n        let first = true;\n        for (let prevCol = 0; prevCol < n; prevCol++) {\n            const prev = dp[(row - 1)][prevCol];\n            const step = moveCost[prevCol][col];\n            const total = prev + step;\n            if (first || total < best) {\n                best = total;\n                first = false;\n            }\n        }\n        dp[row][col] = (grid[row][col] + best);\n    }\n}\nlet out = dp[(m - 1)][0];\nfor (let col = 0; col < n; col++) {\n    const val = dp[(m - 1)][col];\n    if (val < out) {\n        out = val;\n    }\n}\nreturn out;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":11,"11":12,"12":13,"13":14,"14":15,"15":16,"16":17,"17":20,"18":23,"19":24,"20":25,"21":26,"22":27,"23":30},"statementBundles":{"5":{"startLine":5,"endLine":6},"16":{"startLine":17,"endLine":19},"17":{"startLine":20,"endLine":22},"22":{"startLine":27,"endLine":29}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const m = grid.length;\nconst n = grid[0].length;\nconst dp = Array.from({ length: m }, () => Array(n).fill(0));\nfor (let col = 0; col < n; col++) {\n    dp[0][col] = grid[0][col];\n}\nfor (let row = 1; row < m; row++) {\n    for (let col = 0; col < n; col++) {\n        let best = dp[0][0];\n        let first = true;\n        for (let prevCol = 0; prevCol < n; prevCol++) {\n            const prev = dp[(row - 1)][prevCol];\n            const step = moveCost[prevCol][col];\n            const total = prev + step;\n            if (first || total < best) {\n                best = total;\n                first = false;\n            }\n        }\n        dp[row][col] = (grid[row][col] + best);\n    }\n}\nlet out = dp[(m - 1)][0];\nfor (let col = 0; col < n; col++) {\n    const val = dp[(m - 1)][col];\n    if (val < out) {\n        out = val;\n    }\n}\nreturn out;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":11,"11":12,"12":13,"13":14,"14":15,"15":16,"16":17,"17":20,"18":23,"19":24,"20":25,"21":26,"22":27,"23":30},"statementBundles":{"5":{"startLine":5,"endLine":6},"16":{"startLine":17,"endLine":19},"17":{"startLine":20,"endLine":22},"22":{"startLine":27,"endLine":29}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int m = grid.size();\nint n = grid.get(0).size();\nList<List<Integer>> dp = new ArrayList<>();\nfor (int i = 0; i < m; i++) {\n    List<Integer> items0 = new ArrayList<>();\n    for (int index = 0; index < n; index++) {\n        items0.add(0);\n    }\n    dp.add(items0);\n}\nfor (int col = 0; col < n; col++) {\n    dp.get(0).set(col, grid.get(0).get(col));\n}\nfor (int row = 1; row < m; row++) {\n    for (int col = 0; col < n; col++) {\n        int best = dp.get(0).get(0);\n        boolean first = true;\n        for (int prevCol = 0; prevCol < n; prevCol++) {\n            int prev = dp.get(row - 1).get(prevCol);\n            int step = moveCost.get(prevCol).get(col);\n            int total = prev + step;\n            if (first || total < best) {\n                best = total;\n                first = false;\n            }\n        }\n        dp.get(row).set(col, (grid.get(row).get(col) + best));\n    }\n}\nint out = dp.get(m - 1).get(0);\nfor (int col = 0; col < n; col++) {\n    int val = dp.get(m - 1).get(col);\n    if (val < out) {\n        out = val;\n    }\n}\nreturn out;","lineMap":{"1":1,"2":2,"3":3,"4":11,"5":12,"6":14,"7":15,"8":16,"9":17,"10":18,"11":19,"12":20,"13":21,"14":22,"15":23,"16":24,"17":27,"18":30,"19":31,"20":32,"21":33,"22":34,"23":37},"statementBundles":{"3":{"startLine":3,"endLine":10},"5":{"startLine":12,"endLine":13},"16":{"startLine":24,"endLine":26},"17":{"startLine":27,"endLine":29},"22":{"startLine":34,"endLine":36}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int m = grid.Count;\nint n = grid[0].Count;\nList<List<int>> dp = Enumerable.Range(0, m).Select(_ => Enumerable.Repeat<int>(0, n).ToList()).ToList();\nfor (int col = 0; col < n; col++) {\n    dp[0][col] = grid[0][col];\n}\nfor (int row = 1; row < m; row++) {\n    for (int col = 0; col < n; col++) {\n        int best = dp[0][0];\n        bool first = true;\n        for (int prevCol = 0; prevCol < n; prevCol++) {\n            int prev = dp[row - 1][prevCol];\n            int step = moveCost[prevCol][col];\n            int total = prev + step;\n            if (first || total < best) {\n                best = total;\n                first = false;\n            }\n        }\n        dp[row][col] = grid[row][col] + best;\n    }\n}\nint out_ = dp[m - 1][0];\nfor (int col = 0; col < n; col++) {\n    int val = dp[m - 1][col];\n    if (val < out_) {\n        out_ = val;\n    }\n}\nreturn out_;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":11,"11":12,"12":13,"13":14,"14":15,"15":16,"16":17,"17":20,"18":23,"19":24,"20":25,"21":26,"22":27,"23":30},"statementBundles":{"5":{"startLine":5,"endLine":6},"16":{"startLine":17,"endLine":19},"17":{"startLine":20,"endLine":22},"22":{"startLine":27,"endLine":29}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int m = grid.size();\nint n = grid[0].size();\nvector<vector<int>> dp = vector<vector<int>>(m, vector<int>(n, 0));\nfor (int col = 0; col < n; col++) {\n    dp[0][col] = grid[0][col];\n}\nfor (int row = 1; row < m; row++) {\n    for (int col = 0; col < n; col++) {\n        int best = dp[0][0];\n        bool first = true;\n        for (int prev_col = 0; prev_col < n; prev_col++) {\n            int prev = dp[(row - 1)][prev_col];\n            int step = move_cost[prev_col][col];\n            int total = prev + step;\n            if ((first || total < best)) {\n                best = total;\n                first = false;\n            }\n        }\n        dp[row][col] = (grid[row][col] + best);\n    }\n}\nint out = dp[(m - 1)][0];\nfor (int col = 0; col < n; col++) {\n    int val = dp[(m - 1)][col];\n    if (val < out) {\n        out = val;\n    }\n}\nreturn out;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":11,"11":12,"12":13,"13":14,"14":15,"15":16,"16":17,"17":20,"18":23,"19":24,"20":25,"21":26,"22":27,"23":30},"statementBundles":{"5":{"startLine":5,"endLine":6},"16":{"startLine":17,"endLine":19},"17":{"startLine":20,"endLine":22},"22":{"startLine":27,"endLine":29}}}}}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the rolling rule into code","workspacePanel":"visualizer","summary":"Each column is its value plus the cheapest arrival, and the move cost is keyed by the previous value.","ctaLabel":"Start coding","body":["Seed a rolling array with the first row's values. Then for each row below, open a fresh array and fill every column.","For a column, scan all previous columns, take the cheapest dp[prev] plus the move cost charged for leaving that column's value, and add this cell's own value. Roll the finished row forward, and return the smallest value in the final row."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"grid":[[5,3],[4,0],[2,1]],"nums":[5,3],"labels":{"nums":"dp","grid":"grid","r":"row","c":"col"},"i":0}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the rolling DP","eyebrow":"Code the rule","summary":"Now build the rolling array: seed it with the first row, then walk each row below, and for every column scan all previous columns, cost each arrival with the move keyed by the previous value, keep the cheapest plus this cell's value and roll the row forward, then return the smallest last-row cost.","workspacePanel":"code","checkpoints":[{"id":"init-first-row","title":"Seed the first-row costs","description":"Start the rolling array with the cost to land on each column of the first row, which is just that cell's grid value.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_recurrence_state","scope":"init-rolling-states","readMode":"dp-value-query-v1"}]},"commonMistakes":["Seeding from only one column instead of every first-row column","Starting every entry at zero instead of the first row's values"],"hint":"Copy the whole first row into the rolling array, one entry per column."},{"id":"init-current-row","title":"Open a fresh row to fill","description":"For each later row, build a new array of best costs so the previous row's values stay readable while you compute this one.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_sentinel_indexed_state_store","scope":"init-dp","readMode":"dp-value-query-v1"}]},"commonMistakes":["Overwriting the previous row before all of its costs have been read","Carrying stale values from the row before into the new one"],"hint":"Allocate a new array sized to the number of columns before filling it."},{"id":"scan-rows","title":"Walk the rows top to bottom","description":"Process each row below the first in turn, since each one's costs are built from the row directly above it.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_indexed_state_space","scope":"outer-loop","readMode":"dp-value-query-v1"}]},"commonMistakes":["Stopping before the final row and never costing the destination","Starting at the first row and adding its values a second time"],"hint":"Loop the row index from the second row down to the last."},{"id":"scan-previous-columns","title":"Try every previous column","description":"For a given current column, consider arriving from each column of the previous row, because a move may cross to any column.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_nested_choice_state_space","scope":"inner-loop","readMode":"dp-value-query-v1"}]},"commonMistakes":["Only considering the column directly above","Only considering the neighboring columns"],"hint":"Inside the current-column loop, scan all previous columns as candidate sources."},{"id":"compute-transition","title":"Cost one arrival","description":"Combine the stored cost at the previous column with the move cost charged for leaving that previous cell's value and landing on this column.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"computes_recurrence_transition","scope":"compute-next-states","readMode":"dp-value-query-v1"}]},"commonMistakes":["Keying the move cost by the previous column index instead of the previous cell's value","Adding only the move cost and dropping the previous column's stored cost"],"hint":"The candidate is the previous column's stored cost plus the move cost keyed by the previous cell's value and this column."},{"id":"write-current-cost","title":"Keep the cheapest arrival","description":"Store this column's grid value plus the cheapest candidate found, then make the finished row the one the next row reads from.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"writes_recurrence_state","scope":"keep-better-outcome","readMode":"dp-value-query-v1"}]},"commonMistakes":["Storing the move cost alone and dropping this cell's grid value","Never replacing the rolling array with the row you just filled"],"hint":"Write the current cell as its grid value plus the best candidate, then roll the finished row forward."},{"id":"return-minimum-last-row","title":"Read off the cheapest finish","description":"Any column of the last row is a valid finish, so the answer is the smallest stored cost across that final row.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_indexed_terminal_state","scope":"return-result","readMode":"dp-value-query-v1"}]},"commonMistakes":["Returning one fixed last column instead of the cheapest","Returning the whole final row instead of its minimum"],"hint":"Return the minimum entry of the final rolling array."}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Each column of dp holds the cheapest total to reach it; the next row is built from that alone.","workspacePanel":"code","body":["Enumerating routes multiplied n choices per row, so the work grew as n to the m. Carrying just the cheapest cost to each column collapses that into one sweep per row.","The move cost is keyed by the value you leave. Using the column index there quietly breaks the table."],"takeaways":[{"title":"Cheapest arrival, plus the cell","body":"current[col] = grid[row][col] + min over prev of dp[prev] + moveCost[grid[row-1][prev]][col] turns the whole grid into one local rule."},{"title":"One number per column is enough","body":"The next row only asks how cheaply each column was reached, so a rolling array of best costs replaces every full route."},{"title":"O(m times n squared) time, O(n) space","body":"Each of the m rows fills n columns by scanning n previous columns, and only one row of costs is kept at a time, down from the exponential route enumeration."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
