Problem Solving with Go course

Stacks, Queues and SearchDFS and Flood Fill

Problem Solving with Go

Display

Theme

Stacks, Queues and Search · Test exercise

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.

  1. 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 (0 if the cell already has colour).
  2. 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.
main.go
package main

import (
	"fmt"
	"io"
	"os"
	"strings"
)

// Up, down, left, right as {row, column}.
var dirs = [][2]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}

// fill works like a paint bucket: it gives colour to the cell (r, c) and to every cell
// joined to it up, down, left or right that has the same colour it had. It returns how
// many cells changed.
func fill(grid [][]byte, r, c int, colour byte) int {
	// TODO: remember the old colour, then paint cells as you push them on a stack
	return 0
}

// regions counts the areas of one colour joined up, down, left or right, and returns
// how many there are and the number of cells in the largest.
func regions(grid []string) (count, largest int) {
	// TODO: start a search from every cell not seen yet
	return 0, 0
}

func main() {
	data, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Println("could not read input:", err)
		return
	}
	rows := strings.Split(strings.TrimSpace(strings.ReplaceAll(string(data), "\r\n", "\n")), "\n")
	count, largest := regions(rows)
	fmt.Println("regions:", count, "largest:", largest)

	grid := make([][]byte, len(rows))
	for r, row := range rows {
		grid[r] = []byte(row)
	}
	fmt.Println("background cells painted:", fill(grid, 0, 0, ' '))
	for _, row := range grid {
		fmt.Println(string(row))
	}
}
Go runtime not loaded yet

6 lines · 66 B of the 1 MB limit. Submit always uses the lesson's own input.