Largest Crop Field

Easy · Graphs, BFS & DFS · about 15 min

A drone photographs a farm and turns it into a grid: 1 means the cell is planted, 0 means it is bare. A field is a group of planted cells joined by steps up, down, left or right (diagonals do not join cells).

Return the number of cells in the largest field. Return 0 if nothing is planted or the grid is empty.

Example:

largest_field([[1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1]]) → 4

(The top-left field has 3 cells, the bottom-right field has 4.)

Hints

  • Every unvisited planted cell is the start of a new field.
  • From that start, visit all planted neighbours in four directions, marking each one so it is never counted twice, and count how many you visit.
  • Compare each field's count with the best so far.

Learn the pattern first: the Graphs, BFS & DFS lesson.

More Graphs, BFS & DFS problems