Last active
September 11, 2019 22:47
-
-
Save sebinsua/db2010b2934cfb863855b159640d8531 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const floodFill = (grid = [], startPoint, newColor) => { | |
| const [y, x] = startPoint; | |
| const startColor = grid[y][x]; | |
| const points = [startPoint]; | |
| while (points.length) { | |
| const [y, x] = points.shift(); | |
| grid[y][x] = null; | |
| if (y - 1 >= 0 && grid[y - 1][x] === startColor) { | |
| points.push([y - 1, x]); | |
| } | |
| if (x + 1 < grid[y].length && grid[y][x + 1] === startColor) { | |
| points.push([y, x + 1]); | |
| } | |
| if (y + 1 < grid.length && grid[y + 1][x] === startColor) { | |
| points.push([y + 1, x]); | |
| } | |
| if (x - 1 >= 0 && grid[y][x - 1] === startColor) { | |
| points.push([y, x - 1]); | |
| } | |
| } | |
| for (let y = 0; y < grid.length; y++) { | |
| for (let x = 0; x < grid[y].length; x++) { | |
| if (grid[y][x] === null) { | |
| grid[y][x] = newColor; | |
| } | |
| } | |
| } | |
| return grid; | |
| }; | |
| function printGrid(grid = []) { | |
| const height = grid.length; | |
| let gridStr = ""; | |
| for (let y = 0; y < height; y++) { | |
| gridStr += `${grid[y].join(" ")}\n`; | |
| } | |
| console.log(gridStr); | |
| } | |
| const grids = [ | |
| { | |
| grid: [ | |
| [0, 0, 3, 3, 3], | |
| [0, 3, 3, 0, 3], | |
| [3, 3, 3, 0, 3], | |
| [0, 3, 0, 0, 3], | |
| [0, 0, 0, 0, 0] | |
| ], | |
| point: [2, 2] | |
| }, | |
| { | |
| grid: [ | |
| [0, 1, 0, 2, 0], | |
| [0, 1, 0, 1, 0], | |
| [0, 0, 0, 1, 0], | |
| [0, 0, 0, 1, 0], | |
| [0, 0, 0, 1, 0] | |
| ], | |
| point: [0, 0] | |
| } | |
| ]; | |
| const fillColor = 5; | |
| for (let { grid, point } of grids) { | |
| console.log("original grid:"); | |
| printGrid(grid); | |
| const newGrid = floodFill(grid, point, fillColor); | |
| console.log("filled grid:"); | |
| printGrid(newGrid); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment