v9.1.1
Menu

Seam Carving - Find Minimum Energy Path

mediumFREEDynamic ProgrammingDynamic Programming, MatrixCV - DSA

Problem Statement

Seam Carving is a content-aware image resizing technique that removes pixels along low-energy "seams" (paths) to reduce image width while preserving important features.

Given a 2D energy matrix where each cell represents the "energy" (importance) of a pixel, find the minimum total energy of a vertical seam from top to bottom.

A vertical seam is a path of pixels from top row to bottom row, where each pixel in the seam is connected to the pixel directly below it or diagonally below-left or below-right (i.e., you can move to (row+1, col-1), (row+1, col), or (row+1, col+1)).

Constraints

  • 1≤rows,cols≤1001 \leq rows, cols \leq 100
  • 0≤energy[i][j]≤10000 \leq energy[i][j] \leq 1000

Example

For energy matrix:

[[1, 4, 3],
 [5, 2, 6],
 [9, 8, 7]]

The minimum seam goes: 1 → 2 → 7 = 10

Example

Input
energy = [[1, 4, 3], [5, 2, 6], [9, 8, 7]]
Output
10
Reasoning
  • Input: energy is a 3×33 \times 3 grid. Each number is a pixel's importance, so a low-energy seam removes the least visible content.
  • A vertical seam takes exactly one pixel per row, and from row to row it may shift by at most one column. From the top-left 11, row 1 can only continue to 55 or 22; the 66 is out of reach.
  • Compare a few legal seams: 1+2+7=101 + 2 + 7 = 10, 1+2+8=111 + 2 + 8 = 11, 3+2+7=123 + 2 + 7 = 12, 4+2+7=134 + 2 + 7 = 13, 1+5+8=141 + 5 + 8 = 14, 3+6+7=163 + 6 + 7 = 16.
  • None beats 1+2+71 + 2 + 7, so the output is 10: the total energy as one integer, not the path.
  • Notice the best seam zigzags through the centre 22. Taking each row's cheapest pixel also gives 1+2+71 + 2 + 7 here, but only by luck: those pixels can sit more than one column apart, and a seam must stay connected.

Learn this in

More from CV - DSA

solution.py

Test results

Sign in to run your code against the test cases.