1
var colorBorder = function (grid, row, col, color) {3
const n = grid[0].length;4
const dirs = [-1, 0, 1, 0, -1];8
for (let i = 0; i < m; i++) {9
res[i] = new Array(n).fill(-1);12
const val = grid[row][col];15
const visited = new Set();17
visited.add(`${row}#${col}`);18
stack.push([row, col]);20
while (stack.length > 0) {21
const [currRow, currCol] = stack.pop();23
let isConnected = true;25
for (let i = 0; i < dirs.length - 1; i++) {26
const neiRow = currRow + dirs[i];27
const neiCol = currCol + dirs[i + 1];29
if (withinBound(neiRow, neiCol)) {30
if (!visited.has(`${neiRow}#${neiCol}`)) {31
if (grid[neiRow][neiCol] === val) {32
visited.add(`${neiRow}#${neiCol}`);33
stack.push([neiRow, neiCol]);41
if (isBorder(currRow, currCol) || !isConnected)42
res[currRow][currCol] = color;45
for (let i = 0; i < m; i++) {46
for (let j = 0; j < n; j++) {47
if (res[i][j] === -1) {48
res[i][j] = grid[i][j];55
function withinBound(row, col) {56
return row >= 0 && col >= 0 && row < m && col < n;59
function isBorder(row, col) {60
return row === 0 || col === 0 || row === m - 1 || col === n - 1;