diff --git a/src/algorithms/Recursion/FloodFill.js b/src/algorithms/Recursion/FloodFill.js new file mode 100644 index 0000000..295ce98 --- /dev/null +++ b/src/algorithms/Recursion/FloodFill.js @@ -0,0 +1,18 @@ +export function floodFill(mat, x, y, targetColor, newColor, steps = []) { + const rows = mat.length; + const cols = mat[0].length; + + if (x < 0 || y < 0 || x >= rows || y >= cols) return; + if (mat[x][y] !== targetColor) return; + + steps.push({ x, y }); + + mat[x][y] = newColor; + + floodFill(mat, x + 1, y, targetColor, newColor, steps); + floodFill(mat, x - 1, y, targetColor, newColor, steps); + floodFill(mat, x, y + 1, targetColor, newColor, steps); + floodFill(mat, x, y - 1, targetColor, newColor, steps); + + return steps; +} diff --git a/src/components/Recursion/FloodFill.jsx b/src/components/Recursion/FloodFill.jsx new file mode 100644 index 0000000..81b0e3d --- /dev/null +++ b/src/components/Recursion/FloodFill.jsx @@ -0,0 +1,142 @@ +import React, { useState } from "react"; +import { floodFill } from "@/algorithms/Recursion/FloodFill"; +export default function FloodFillVisualizer() { + const rows = 20; + const cols = 20; + + const generateGrid = () => { + const grid = []; + for (let i = 0; i < rows; i++) { + const row = []; + for (let j = 0; j < cols; j++) { + row.push(Math.random() > 0.3 ? 1 : 0); + } + grid.push(row); + } + return grid; + }; + + const [grid, setGrid] = useState(generateGrid()); + const [speed, setSpeed] = useState(200); + const [isRunning, setIsRunning] = useState(false); + + const source = { x: 0, y: 0 }; + + const startFloodFill = () => { + if (isRunning) return; + + const mat = grid.map((row) => [...row]); + const steps = []; + floodFill(grid.map((row) => [...row]), source.x, source.y, 1, 2, steps); + + animateFill(steps); + }; + + const animateFill = (steps) => { + let i = 0; + setIsRunning(true); + + const interval = setInterval(() => { + if (i >= steps.length) { + clearInterval(interval); + setIsRunning(false); + return; + } + + const { x, y } = steps[i]; + setGrid((prev) => { + const newGrid = prev.map((row) => [...row]); + newGrid[x][y] = 2; + return newGrid; + }); + + i++; + }, speed); + }; + + return ( +