ArticleslgStudy

computer science

Flood fill

Flood fill is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Flood fill rather than just read about it. In short: Flood fill, also called seed fill, is a flooding algorithm that determines and alters the area connected to a given node in a multi-dimensional array with some matching attribute. It is used in the "bucket" fill tool of paint programs to fill connected, similarly colored areas with a different color, and in games such as Go and Minesweeper for determining which pieces are cleared.

Flood fill — main illustration
Flood fill — illustration

Key takeaways

  • Flood fill belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Flood fill to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Flood fill from memory before moving on to harder problems.

Reference excerpt

Flood fill, also called seed fill, is a flooding algorithm that determines and alters the area connected to a given node in a multi-dimensional array with some matching attribute. It is used in the "bucket" fill tool of paint programs to fill connected, similarly colored areas with a different color, and in games such as Go and Minesweeper for determining which pieces are cleared. A variant called boundary fill uses the same algorithms but is defined as the area connected to a given node that does not have a particular attribute. Note that flood filling is not suitable for drawing filled polygons, as it will miss some pixels in more acute corners. Instead, see Even-odd rule and Nonzero-rule.

Algorithm parameters

The traditional flood-fill algorithm takes three parameters: a start node, a target color, and a replacement color. The algorithm looks for all nodes in the array that are connected to the start node by a path of the target color and changes them to the replacement color. For a boundary-fill, in place of the target color, a border color would be supplied. In order to generalize the algorithm in the common way, the following descriptions will instead have two routines available. One called Inside which returns true for unfilled points that, by their color, would be inside the filled area, and one called Set which fills a pixel/node. Any node that has Set called on it must then no longer be Inside. Depending on whether we consider nodes touching at the corners connected or not, we have two variations: eight-way and four-way respectively.

Stack-based recursive implementation (four-way) The earliest-known, implicitly stack-based, recursive, four-way flood-fill implementation goes as follows:

Flood-fill (node): 1. If node is not Inside return. 2. Set the node 3. Perform Flood-fill one step to the south of node. 4. Perform Flood-fill one step to the north of node 5. Perform Flood-fill one step to the west of node 6. Perform Flood-fill one step to the east of node 7. Return.

Though easy to understand, the implementation of the algorithm used above is impractical in languages and environments where stack space is severely constrained (e.g. Microcontrollers).

Moving the recursion into a data structure

Moving the recursion into a data structure (either a stack or a queue) prevents a stack overflow. It is similar to the simple recursive solution, except that instead of making recursive calls, it pushes the nodes onto a stack or queue for consumption, with the choice of data structure affecting the proliferation pattern:

Flood-fill (node): 1. Set Q to the empty queue or stack. 2. Add node to the end of Q. 3. While Q is not empty: 4. Set n equal to the first element of Q. 5. Remove first element from Q. 6. If n is Inside: Set the n Add the node to the west of n to the end of Q. Add the node to the east of n to the end of Q. Add the node to the north of n to the end of Q. Add the node to the south of n to the end of Q. 7. Continue looping until Q is exhausted. 8. Return.

Further potential optimizations Check and set each node's pixel color before adding it to the stack/queue, reducing stack/queue size. Use a loop for the east–west directions, queuing pixels above/below as you go (making it similar to the span filling algorithms, below). Interleave two or more copies of the code with extra stacks/queues, to allow out-of-order processors more opportunity to parallelize. Use multiple threads (ideally with slightly different visiting orders, so they don't stay in the same area).

Advantages Very simple algorithm - easy to make bug-free.

Disadvantages Uses a lot of memory, particularly when using a stack. Tests most filled pixels a total of four times. Not suitable for pattern filling, as it requires pixel test results to change. Access pattern is not cache-friendly, for the queuing variant. Cannot easily optimize for multi-pixel words or bitplanes.

Span filling

It's possible to optimize things further by working primarily with spans, a row with constant y. The first published complete example works on the following basic principle.

Starting with a seed point, fill left and right. Keep track of the leftmost filled point lx and rightmost filled point rx. This defines the span. Scan from lx to rx above and below the seed point, searching for new seed points to continue with. As an optimisation, the scan algorithm does not need restart from every seed point, but only those at the start of the next span. Using a stack explores spans depth first, whilst a queue explores spans breadth first.

fn fill(x, y): if not Inside(x, y) then return let s = new empty stack or queue Add (x, y) to s while s is not empty: Remove an (x, y) from s let lx = x while Inside(lx - 1, y): Set(lx - 1, y) lx = lx - 1 while Inside(x, y): Set(x, y) x = x + 1 scan(lx, x - 1, y + 1, s) scan(lx, x - 1, y - 1, s)

fn scan(lx, rx, y, s): let span_added = false for x in lx .. rx: if not Inside(x, y): span_added = false else if not span_added: Add (x, y) to s span_added = true

Over time, the following optimizations were realized:

When a new scan would be entirely within a grandparent span, it would certainly only find filled pixels, and so wouldn't need queueing. Further, when a new scan overlaps a grandparent span, only the overhangs (U-turns and W-turns) need to be scanned. It's possible to fill while scanning for seeds The final, combined-scan-and-fill span filler was then published in 1990. In what follows, the queue or stack contains segments, each consisting of four values (x1, x2, y, dy), where x1 and x2 are the left and right ends of the segment, y is the current line, and dy is 1 or -1 to indicate that line's position relative to the parent segment. If dy is 1, the parent segment is on the line above, and if dy is -1 the parent segment is on the line below. In pseudo-code form:

… excerpt ends here. Continue reading the full article.

Illustrations

Flood fill: Recursive flood fill with 4 directions
Recursive flood fill with 4 directions
Flood fill: Recursive flood fill with 8 directions
Recursive flood fill with 8 directions
Flood fill illustration
Flood fill illustration
Flood fill: Scanline fill using a stack for storage
Scanline fill using a stack for storage

Worked examples

Example 1 — a first encounter with Flood fill

Start with the simplest possible case. Write down what Flood fill claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Flood fill before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Flood fill ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Flood fill

In research
Flood fill appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Flood fill in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Flood fill is common in secondary-school and first-year university syllabi. It links to neighbouring topics Computer graphics algorithms, Flooding algorithms, so understanding it makes those chapters shorter.
In everyday life
Look for Flood fill outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Flood fill” →

How to study Flood fill in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Flood fill means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Flood fill out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Flood fill in simple terms?

Flood fill, also called seed fill, is a flooding algorithm that determines and alters the area connected to a given node in a multi-dimensional array with some matching attribute. It is used in the "bucket" fill tool of paint programs to fill connected, similarly colored areas with a different colo…

Why does Flood fill matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Flood fill?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Flood fill.

Tags

  • Computer graphics algorithms
  • Flooding algorithms

Keep exploring