DFS and Flood Fill
The paint bucket in a drawing program is a search: click one pixel, and every pixel of the same colour joined to it changes too. That's flood fill, and the same idea answers lots of puzzle questions: how big is this field, how many separate islands are there, which cells can the water reach.
Order doesn't matter, so use a stack
For shortest paths, BFS and its queue matter: the order of exploring is what makes the distances right. For flood fill, you only need every joined cell, in any order. A stack is simplest. Exploring with a stack goes deep along one direction before coming back, so it's called depth-first search (DFS).
stack := [][2]int{{r, c}}
seen[r][c] = true
for len(stack) > 0 {
cur := stack[len(stack)-1]
stack = stack[:len(stack)-1]
// visit cur, then push its neighbours that are the same and not seen
}
The only difference from BFS is which end you take from. Everything else stays: mark cells as seen when you push them, check the edges of the grid, and look at four (or eight) neighbours.
DFS is often written with recursion: a function that calls itself for every neighbour. That is short and pretty, but every call waits on top of the previous one, and a large area means a very deep pile of calls. A slice as a stack has no such limit.
Counting regions
To count separate areas, loop over every cell. When you find a cell that no search has seen yet, it starts a new region: add one to the count and run a flood fill from it, marking everything it reaches. When the loop ends, every cell belongs to exactly one region.
With a paint bucket you can skip the seen grid: a cell painted in the new colour no longer matches the old colour, so it won't be pushed again. Watch out for one trap: if the new colour equals the old one, nothing ever stops matching. Check for that first.
Task
This lesson's input is a small piece of pixel art: every character is one pixel's colour.
- Complete
fill(grid [][]byte, r, c int, colour byte) int: paint(r, c)and every cell joined to it up, down, left or right with the same colour it had. Return how many cells changed (0if the cell already hascolour). - Complete
regions(grid []string) (count, largest int): how many areas of one colour there are, joined up, down, left or right, and how many cells the largest has.