Community

Start a Thread


Notifications
Subscribe You’re not receiving notifications from this thread.

Flood Fill Paintbucket (Main Thread)

Here is the interview question prompt, presented for reference.

Imagine the implementation for the paintbucket feature in Microsoft Paint, or how certain image filters work. You click on a specific pixel on a screen, and every similar-colored neighboring pixel would change to your selected color. Let's implement a simpler version of that feature.

You're given a n x n matrix array of numbers. Let's say you'd like to replace all similar and connected cells of a certain number with another, starting at column 0 and row 0.

So here's your input:

const input = [
  [1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 0],
  [1, 0, 0, 1, 1, 0, 1],
  [1, 2, 1, 2, 1, 2, 0],
  [1, 2, 1, 2, 2, 2, 0],
  [1, 2, 2, 2, 1, 2, 0],
  [1, 1, 1, 1, 1, 2, 1]
]

And the final result of starting at column 0 and row 0 would be as follows:

// floodFill(matrix, startingRow, startingCol, newValue)
floodFill(input, 0, 0, 3);
// [
//   [3, 3, 3, 3, 3, 3, 3],
//   [3, 3, 3, 3, 3, 3, 0],
//   [3, 0, 0, 3, 3, 0, 1],
//   [3, 2, 1, 2, 3, 2, 0],
//   [3, 2, 1, 2, 2, 2, 0],
//   [3, 2, 2, 2, 3, 2, 0],
//   [3, 3, 3, 3, 3, 2, 1]
// ]

Notice how all the 1s that were bordering the original 1 in column 0 and row 0 have been transformed to 3.

Constraints

  • Given matrix contains non negative integers
  • The array is 0-indexed
  • Let |V|, |E| represent the number of vertices and edges of the graph (if you consider the matrix as a graph)
  • Expected time complexity : O(|V|)
  • Expected space complexity : O(|V|) considering the call stack

You can see the full challenge with visuals at this link.

Challenges • Asked over 6 years ago by Jake from AlgoDaily

Jake from AlgoDaily Commented on Nov 30, 2017:

This is the main discussion thread generated for Flood Fill Paintbucket.