Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let myMatrix = [
- [0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 1],
- [0, 0, 1, 1, 0, 1, 1, 0],
- [0, 0, 1, 0, 0, 0, 1, 0],
- [0, 0, 0, 0, 0, 0, 1, 0],
- [1, 1, 1, 1, 1, 0, 1, 0],
- [0, 0, 0, 0, 1, 1, 1, 1],
- [0, 0, 1, 0, 0, 0, 0, 0]
- ];
- function printMatrix(matrix: number[][]){
- for(let i=0; i< matrix.length; i++){
- console.log(matrix[i].join(""))
- }
- }
- function floodFill(matrix: number[][], x: number, y: number) {
- const matrixCopy : number[][]= JSON.parse(JSON.stringify(matrix));
- const fillColor = 8
- let toFill = [[x,y]];
- let fillCounter = 0;
- while(toFill.length >0 && fillCounter < 100){
- fillCounter++;
- const tested = toFill.pop()
- if(tested == undefined)
- return -1;
- const [tx, ty] = tested;
- matrixCopy[ty][tx] = fillColor
- if(tx > 0 && matrixCopy[ty][tx-1]== 0)
- toFill.push([tx-1, ty])
- if(ty > 0 && matrixCopy[ty-1][tx]== 0)
- toFill.push([tx, ty-1])
- if(tx < matrixCopy[0].length-1 && matrixCopy[ty][tx+1]== 0)
- toFill.push([tx+1, ty])
- if(ty < matrixCopy.length-1 && matrixCopy[ty+1][tx]== 0)
- toFill.push([tx, ty+1])
- }
- printMatrix(matrixCopy)
- return fillCounter;
- }
- console.log(floodFill(myMatrix, 0, 1))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement