Flood fill algorithm in javascript

Flood fill, also called seed fill, is an algorithm that determines and alters the area connected to a given node in a multi-dimensional array with some matching attribute. It is used in the “bucket” fill tool of paint programs to fill connected, similarly-colored areas with a different color, and in games such as Go and Minesweeper for determining which pieces are cleared.

In this article, I will show you how to implement a flood fill algorithm in javascript with visualization to understand it easily


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;

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

إرسال تعليق (0)
أحدث أقدم