Implementing Flood Fill Algorithm in JavaScript for Area Coloring

The flood fill algorithm, also known as seed fill, is a powerful algorithm used to determine and modify connected areas in a multi-dimensional array based on a given attribute. This algorithm is commonly employed in paint programs to fill connected areas with different colors and in games like Go and Minesweeper to determine cleared pieces. In this article, we will explore how to implement a flood fill algorithm in JavaScript. The implementation will include visualization to enhance understanding.

JavaScript Code Implementation:

Below is the JavaScript code that demonstrates the implementation of the flood fill algorithm:


const map = [
  ['#', '#', '#', '#', '#', '#', '#', '#', '#'],
  ['#', '-', '-', '-', '#', '-', '-', '-', '#'],
  ['#', '-', '-', '-', '#', '-', '-', '-', '#'],
  ['#', '-', '-', '#', '-', '-', '-', '-', '#'],
  ['#', '#', '#', '-', '-', '-', '#', '#', '#'],
  ['#', '-', '-', '-', '-', '#', '-', '-', '#'],
  ['#', '-', '-', '-', '#', '-', '-', '-', '#'],
  ['#', '-', '-', '-', '#', '-', '-', '-', '#'],
  ['#', '#', '#', '#', '#', '#', '#', '#', '#'],
];


function floodFillRec(i, j, oldColor, newColor) {

  // Check the boundary condition
  if (i < 0 || i >= map.length || j < 0 || j >= map[i].length) return;
  if (map[i][j] !== oldColor) return;

  // set the color of node to newColor
  map[i][j] = newColor;


  // Look for neighboring cell
  floodFillRec(i + 1, j, oldColor, newColor);
  floodFillRec(i - 1, j, oldColor, newColor);
  floodFillRec(i, j + 1, oldColor, newColor);
  floodFillRec(i, j - 1, oldColor, newColor);
}

floodFillRec(4, 4, '-', 'f');
map;

Visualization:

Conclusion:

In this article, we learned how to implement the flood fill algorithm in JavaScript. This algorithm allows us to identify and modify connected areas in a multi-dimensional array based on specific attributes. By leveraging the flood fill algorithm, we can create interesting applications like area coloring tools. Feel free to experiment with different scenarios and expand upon the provided code to further enhance your understanding of this algorithm.

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post