Ctrl K

Cheapest Descent Through a Grid

Medium
You get an n × n grid grid of integers. You walk down it from top to bottom: start in any cell of the first row, and at each step move to the next row, either straight down or one column diagonally. From cell (r, c) you can go to (r + 1, c - 1), (r + 1, c) or (r + 1, c + 1), as long as that cell exists. The cost of a descent is the sum of all cells it visits, from the first row to the last. Return the minimum possible cost.
Example 1
grid=[[4, 9, 1], [3, 2, 8], [6, 5, 7]] → 8

The cheapest way down is 1 → 2 → 5, for a total of 8.

Example 2
grid=[[5, -3], [-8, 10]] → -11

From -3 you can step diagonally onto -8, giving -11.

Example 3
grid=[[42]] → 42
Constraints
  • n == len(grid) == len(grid[i])
  • 1 ≤ n ≤ 100
  • -100 ≤ grid[i][j] ≤ 100
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWarehouse Cart Routes MediumCheapest Corner-to-Corner Route MediumLargest Solid Square MediumBest Spot for the Turret MediumSteps to the Nearest Zero Medium
loading Python…
Input
grid=[[4, 9, 1], [3, 2, 8], [6, 5, 7]]
Expected
8

Run checks the first 3 tests in your browser. Submit checks all 69 tests on the server, hidden ones included.