|
| 1 | +/** |
| 2 | + * @param {number[][]} grid |
| 3 | + * @param {number} r0 |
| 4 | + * @param {number} c0 |
| 5 | + * @param {number} color |
| 6 | + * @return {number[][]} |
| 7 | + */ |
| 8 | +const colorBorder = function(grid, r0, c0, color) { |
| 9 | + const dirs = [[-1,0], [1,0], [0,1], [0,-1]] |
| 10 | + const c = grid[r0][c0] |
| 11 | + const rows = grid.length |
| 12 | + const cols = grid[0].length |
| 13 | + const visited = Array.from({length: rows}, () => new Array(cols).fill(0)) |
| 14 | + dfs(r0, c0, c, rows, cols, visited, grid, dirs) |
| 15 | + for(let i = 0; i < rows; i++) { |
| 16 | + for(let j = 0; j < cols; j++) { |
| 17 | + if(visited[i][j] === -1) { |
| 18 | + if(i === 0 || j === 0 || i === rows - 1 || j === cols - 1) { |
| 19 | + visited[i][j] = -2 |
| 20 | + } else { |
| 21 | + for(let dir of dirs) { |
| 22 | + if(visited[i + dir[0]][j + dir[1]] === 0) { |
| 23 | + visited[i][j] = -2 |
| 24 | + break |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + for(let i = 0; i < rows; i++) { |
| 32 | + for(let j = 0; j < cols; j++) { |
| 33 | + if(visited[i][j] === -2) grid[i][j] = color |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + return grid |
| 38 | +}; |
| 39 | + |
| 40 | +function dfs(row, col, target, rows, cols, visited, grid, dirs) { |
| 41 | + if(row >= rows || col >= cols || row < 0 || col < 0 || grid[row][col] !== target || visited[row][col] === -1) { |
| 42 | + return |
| 43 | + } |
| 44 | + visited[row][col] = -1 |
| 45 | + for(let dir of dirs) { |
| 46 | + dfs(row + dir[0], col+dir[1], target, rows, cols, visited, grid, dirs) |
| 47 | + } |
| 48 | + |
| 49 | +} |
0 commit comments