Problem Statement
Given a graph, color similarly-colored nodes/areas with the same color.
See this Wikipedia article for an illustration.
General Idea | \(O(V+E) \space or \space O(row+col)\)
The general idea is to select a target/starting node, a target color and a replacement color. We then recursively loop over the starting node’s neighbours, replacing the target color with the replacement color for each node.
There are many variations to this algorithm. This algorithm can be run
on a typical graph (with vertices
and edges
), or, on an implicit 2D graph,
i.e a 2D array.
There is also astack
-based recursive implementation (akin to DFS
) and another
queue
-based implementation, based on BFS
.
The disadvantage of using the stack
-based recursive implementation is that
it is impractical when the dataset is too large or when the stack space is
severely contrained, leading to a stack overflow.
There are also variation when dealing with an implicit 2D graph. Namely, 8-way flood fill or 4-way flood fill, depending on whether we should consider nodes touching at corners connected or not.
Pseudocode for all these different variations are in this Wikipedia article
Code
C++11 code for an 8-way flood fill on an implicit 2D graph, using a stack-based approach.