Island / Matrix Traversal
Treat each grid cell as a graph node and each neighbor as an edge. Then islands, flood fill, enclosed regions, spreading rot and water flow are all one search, started from the right cells.
Overview
A grid is a graph
A grid problem is a graph problem in disguise. Each cell is a node. Two cells are joined when they touch along an edge, so most cells have four neighbors: up, down, left and right. Once you see that, every island question becomes a graph search, and the only decisions left are where to start the search and what to record while it runs.
Put in graph terms, a grid of m rows and n columns has a node for each cell (r, c), with 0 ≤ r < m and 0 ≤ c < n, so m × n nodes in all. Each cell has an edge to (r ± 1, c) and (r, c ± 1) whenever that neighbor is inside the grid, which makes fewer than 2 × m × n edges. The visited mark can be a set of (r, c), a boolean grid, or a changed value in the grid itself.
Keep the four offsets in one list, [(-1, 0), (1, 0), (0, -1), (0, 1)], and write the bounds check once inside the loop over them. Check whether diagonal cells count as neighbors; if they do, the list has eight entries and nothing else changes.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio