Skip to main content

Medium graphs · flood fill · grids

Paint bucket

The paint bucket from every drawing app, one cell at a time.

Write floodFill(grid, row, col, color): grid is rows of small numbers, each a colour. Starting at grid[row][col], repaint that cell and every cell connected to it (up, down, left, right, never diagonal) that has the same starting colour. Return a new grid; do not change the input. If the start cell is already color, return the grid unchanged.

Call show(grid) after each cell you paint and the stage plays the fill spreading.

Example: floodFill([[1, 1, 1], [1, 1, 0], [1, 0, 1]], 1, 1, 2) returns [[2, 2, 2], [2, 2, 0], [2, 0, 1]]. The bottom right 1 is only touching diagonally, so it stays.

Tests you can see

  • floodFill([[1,1,1],[1,1,0],[1,0,1]], 1, 1, 2)[[2,2,2],[2,2,0],[2,0,1]]
  • floodFill([[0,1,0],[0,1,0],[0,1,0]], 0, 2, 3)[[0,1,3],[0,1,3],[0,1,3]]

More tests are hidden. The server runs them all before a time counts.

Call show() while your code works and the run plays back here.

javascriptfloodFill()

Tab indents · Cmd/Ctrl+Enter runs