I've recently learned about the Flood-Fill Algorithm, an algorithm that can take a graph and assign each node a component number in O(N)
time.
For example, a common problem that can be solved efficiently with the Flood-Fill Algorithm would be to find the largest region in a N*N
board, where every node in the region is adjacent to another node with the same ID either directly up, down, to the left, or to the right.
In this board, the largest regions would both be of size 3, made up of all 1s and all 9s respectively.
However, I recently started wondering if we could extend this problem; specifically, if we could find the largest region in a graph such that every node in the region is adjacent to another node with two possible IDs. In the above board, the largest such region is made up of 1s and 9s, and has a size of 7.
Here was my thought process in trying to solve this problem:
Thought 1: O(N^4) Algorithm
We can solve this in O(N^4)
time using a basic flood-fill algorithm. We do this by testing all O(N^2)
pairs of horizontally or vertically adjacent squares. For every pair of squares, if they have different IDs, then we run a flood-fill from one of the two squares.
Then, by modifying the flood-fill algorithm so that it travels to squares with one of the two possible IDs, we can test each pair in O(N^2)
time --> O(N^2) pairs * O(N^2) flood fill per pair = O(N^4) algorithm
.
Then, I had an insight: An Possibly O(N^2) Algorithm
First, we run a regular flood-fill through the board and separate the board into a "component graph" (where each component in the original graph is reduced to a single node).
Now, we do a flood-fill through the edges of the component graph instead of the nodes. We mark each edge with a pair of integers signifying the two IDs inside the two components which it connects, before flood-filling through the edges as if they themselves were nodes.
I believe that this, if implemented correctly, would result in a O(N^2)
algorithm, because an upper bound for the number of edges in a N*N
board is 4*N*N
.
Now, my question is, is my thought process logically sound? If not, can somebody suggest another algorithm to solve this problem?