Flood fill, also called seed fill, is an algorithm that determines the area connected to a given node in a multi-dimensional array

References

Implementations

  • 1
    
    # TODO: Implement in Python
    
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    
    const G = [
      ['#', '#', '#', '#', '#', '#', '#', '#', '#'],
      ['#', '-', '-', '-', '#', '-', '-', '-', '#'],
      ['#', '-', '-', '-', '#', '-', '-', '-', '#'],
      ['#', '-', '-', '#', '-', '-', '-', '-', '#'],
      ['#', '#', '#', '-', '-', '-', '#', '#', '#'],
      ['#', '-', '-', '-', '-', '#', '-', '-', '#'],
      ['#', '-', '-', '-', '#', '-', '-', '-', '#'],
      ['#', '-', '-', '-', '#', '-', '-', '-', '#'],
      ['#', '#', '#', '#', '#', '#', '#', '#', '#'],
    ];
    
    function FloodFill(i, j, oldColor, newColor) {
      if (i < 0 || i >= G.length || j < 0 || j >= G[i].length) return;
      if (G[i][j] !== oldColor) return;
    
      // set the color of node to newColor
      G[i][j] = newColor;
    
      // next step four-way
      FloodFill(i + 1, j, oldColor, newColor);
      FloodFill(i - 1, j, oldColor, newColor);
      FloodFill(i, j + 1, oldColor, newColor);
      FloodFill(i, j - 1, oldColor, newColor);
    }
    
    FloodFill(4, 4, '-', 'a');