|
| 1 | +/** |
| 2 | + * 1034. Coloring A Border |
| 3 | + * https://leetcode.com/problems/coloring-a-border/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an m x n integer matrix grid, and three integers row, col, and color. Each value |
| 7 | + * in the grid represents the color of the grid square at that location. |
| 8 | + * |
| 9 | + * Two squares are called adjacent if they are next to each other in any of the 4 directions. |
| 10 | + * |
| 11 | + * Two squares belong to the same connected component if they have the same color and they are |
| 12 | + * adjacent. |
| 13 | + * |
| 14 | + * The border of a connected component is all the squares in the connected component that are |
| 15 | + * either adjacent to (at least) a square not in the component, or on the boundary of the grid |
| 16 | + * (the first or last row or column). |
| 17 | + * |
| 18 | + * You should color the border of the connected component that contains the square grid[row][col] |
| 19 | + * with color. |
| 20 | + * |
| 21 | + * Return the final grid. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {number[][]} grid |
| 26 | + * @param {number} row |
| 27 | + * @param {number} col |
| 28 | + * @param {number} color |
| 29 | + * @return {number[][]} |
| 30 | + */ |
| 31 | +var colorBorder = function(grid, row, col, color) { |
| 32 | + const rows = grid.length; |
| 33 | + const cols = grid[0].length; |
| 34 | + const visited = new Set(); |
| 35 | + const originalColor = grid[row][col]; |
| 36 | + const borders = new Set(); |
| 37 | + |
| 38 | + function findBorders(r, c) { |
| 39 | + if (r < 0 || r >= rows || c < 0 || c >= cols |
| 40 | + || visited.has(`${r},${c}`) || grid[r][c] !== originalColor) { |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + visited.add(`${r},${c}`); |
| 45 | + |
| 46 | + if (r === 0 || r === rows - 1 || c === 0 || c === cols - 1 |
| 47 | + || (r > 0 && grid[r - 1][c] !== originalColor) |
| 48 | + || (r < rows - 1 && grid[r + 1][c] !== originalColor) |
| 49 | + || (c > 0 && grid[r][c - 1] !== originalColor) |
| 50 | + || (c < cols - 1 && grid[r][c + 1] !== originalColor)) { |
| 51 | + borders.add(`${r},${c}`); |
| 52 | + } |
| 53 | + |
| 54 | + findBorders(r - 1, c); |
| 55 | + findBorders(r + 1, c); |
| 56 | + findBorders(r, c - 1); |
| 57 | + findBorders(r, c + 1); |
| 58 | + } |
| 59 | + |
| 60 | + findBorders(row, col); |
| 61 | + borders.forEach(pos => { |
| 62 | + const [r, c] = pos.split(',').map(Number); |
| 63 | + grid[r][c] = color; |
| 64 | + }); |
| 65 | + |
| 66 | + return grid; |
| 67 | +}; |
0 commit comments