liveBook · Manning

Grid

As explained in Grokking Algorithms, Second Edition

A tabular arrangement of cells that stores computed values for different knapsack capacities.

Suppose you want the most valuable set of items that fits in a knapsack. Instead of tackling the full knapsack at once, draw a grid for smaller versions of the problem. Start with an empty grid; filling its cells builds toward the answer. section 11.3

For a knapsack grid:

  • Give each row an item. A row considers the items available up to that point. section 11.3
  • Give each column a capacity, such as 1, 2, 3, or 4 lb. Each cell records the best value for that capacity and stage of the problem. section 11.3

The first row

A guitar weighs 1 lb and is worth $1,500. With only the guitar available, it fits in the 1 lb knapsack, so that cell has a value of $1,500. It also fits in the larger capacities along that row. section 11.3

Choose the columns carefully. A grid with only whole-pound capacities cannot answer what fits in 3.5 lb of remaining space. Adding a 0.5 lb necklace means the grid needs finer capacity steps. section 11.8

The same grid idea can serve other dynamic programming problems. To compare words for a longest common substring, use the two words as axes; each cell represents a smaller comparison and holds a substring length. What the cells mean—and how to calculate them—depends on the problem. section 11.15 section 11.20

How Grokking Algorithms, Second Edition covers it

How deep it goes
Walks through an empty grid and its first item row, then shows why smaller weight increments require different columns.
Examples
Uses a 1 lb guitar worth $1,500, a 0.5 lb necklace, and a grid comparing misspelled words.
What it assumes
Introduces the dynamic programming grid through an empty knapsack table and a step-by-step walkthrough, without requiring a prior filling formula.
What you can do after
Build it from scratch by assigning knapsack items to rows, capacities to columns, and values to the first item row.
How it connects
Connects grids to dynamic programming, the knapsack problem, subproblems, and longest common substring.

Also explained in

Compare how 8 books explain grid →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Algorithms, Second Edition. The section links point to the parts of the book it draws on.