FastPrepMinimum-Weight Path Through a Matrix

Minimum-Weight Path Through a Matrix

Meta logoMeta● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given a square matrix grid, find the minimum travel cost from its top-left cell to its bottom-right cell. A cell with value -1 is blocked. Every other value is the nonnegative cost of entering that cell.

You may move to any of the eight neighboring cells, including diagonals. The starting cell is not charged; every later entered cell contributes its value. Return the minimum total cost, or -1 if the destination cannot be reached.

Function

minimumWeightedPathCost(grid: int[][]) → int

Examples

Example 1

grid = [[0,5],[2,1]]return = 1

The diagonal enters the destination at cost 1; the starting cell is free.

Example 2

grid = [[0,9,9],[1,-1,1],[2,1,0]]return = 2

Move through the cost-1 cell at (1,0), then the cost-1 cell at (2,1), then the cost-0 destination.

Example 3

grid = [[0,-1,2],[-1,-1,1],[2,1,0]]return = -1

All three neighboring cells of the start are blocked, so no path reaches the destination.

Constraints

  • 1 <= grid.length <= 50 and every row has exactly grid.length cells.
  • Each cell is -1 or an integer from 0 through 1000.
  • Costs are nonnegative, so revisiting a cell cannot improve a minimum-cost path.

More Meta problems

See Meta hiring insights
public int minimumWeightedPathCost(int[][] grid) {
  // Return the minimum sum of entered cell weights.
}
grid[[0,5],[2,1]]
expected1
Checking account…