Advertisement
314ma

floodfill

Dec 20th, 2024
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let myMatrix = [
  2.   [0, 0, 0, 0, 0, 0, 0, 0],
  3.   [0, 0, 0, 0, 0, 0, 0, 1],
  4.   [0, 0, 1, 1, 0, 1, 1, 0],
  5.   [0, 0, 1, 0, 0, 0, 1, 0],
  6.   [0, 0, 0, 0, 0, 0, 1, 0],
  7.   [1, 1, 1, 1, 1, 0, 1, 0],
  8.   [0, 0, 0, 0, 1, 1, 1, 1],
  9.   [0, 0, 1, 0, 0, 0, 0, 0]
  10. ];
  11.  
  12. function printMatrix(matrix: number[][]){
  13.     for(let i=0; i< matrix.length; i++){
  14.             console.log(matrix[i].join(""))
  15.     }
  16. }
  17.  
  18. function floodFill(matrix: number[][], x: number, y: number) {
  19.  
  20.     const matrixCopy : number[][]=  JSON.parse(JSON.stringify(matrix));
  21.     const fillColor = 8
  22.     let toFill = [[x,y]];
  23.     let fillCounter = 0;
  24.     while(toFill.length >0 && fillCounter < 100){
  25.         fillCounter++;
  26.         const tested = toFill.pop()
  27.         if(tested == undefined)
  28.             return -1;
  29.         const [tx, ty] = tested;
  30.         matrixCopy[ty][tx] = fillColor
  31.         if(tx > 0 && matrixCopy[ty][tx-1]== 0)
  32.             toFill.push([tx-1, ty])
  33.         if(ty > 0 && matrixCopy[ty-1][tx]== 0)
  34.             toFill.push([tx, ty-1])
  35.         if(tx < matrixCopy[0].length-1 && matrixCopy[ty][tx+1]== 0)
  36.             toFill.push([tx+1, ty])
  37.         if(ty < matrixCopy.length-1 && matrixCopy[ty+1][tx]== 0)
  38.             toFill.push([tx, ty+1])
  39.     }
  40.     printMatrix(matrixCopy)
  41.     return fillCounter;
  42. }
  43.  
  44. console.log(floodFill(myMatrix, 0, 1))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement