2.7 KiB
id, title, challengeType, dashedName
| id | title | challengeType | dashedName |
|---|---|---|---|
| 6a1d9f98e819ed70a0e994db | Challenge 329: Bucket Fill | 28 | challenge-329 |
--description--
Given a 2D grid, a starting position ([row, col]), and a new value, replace the value at the starting position and all connected cells of the same value with the new value.
- Cells are connected if they are adjacent horizontally or vertically (not diagonally).
Return the updated grid.
--hints--
bucketFill([["R", "G"], ["R", "G"]], [0, 1], "B") should return [["R", "B"], ["R", "B"]].
assert.deepEqual(bucketFill([["R", "G"], ["R", "G"]], [0, 1], "B"), [["R", "B"], ["R", "B"]]);
bucketFill([["Y", "G", "G"], ["Y", "Y", "Y"], ["B", "Y", "R"]], [1, 2], "B") should return [["B", "G", "G"], ["B", "B", "B"], ["B", "B", "R"]].
assert.deepEqual(bucketFill([["Y", "G", "G"], ["Y", "Y", "Y"], ["B", "Y", "R"]], [1, 2], "B"), [["B", "G", "G"], ["B", "B", "B"], ["B", "B", "R"]]);
bucketFill([["O", "O", "P"], ["P", "O", "O"], ["P", "P", "O"]], [2, 0], "R") should return [["O", "O", "P"], ["R", "O", "O"], ["R", "R", "O"]].
assert.deepEqual(bucketFill([["O", "O", "P"], ["P", "O", "O"], ["P", "P", "O"]], [2, 0], "R"), [["O", "O", "P"], ["R", "O", "O"], ["R", "R", "O"]]);
bucketFill([["T", "T", "R", "T"], ["R", "T", "R", "T"], ["R", "T", "R", "T"], ["T", "T", "T", "T"]], [0, 3], "Y") should return [["Y", "Y", "R", "Y"], ["R", "Y", "R", "Y"], ["R", "Y", "R", "Y"], ["Y", "Y", "Y", "Y"]].
assert.deepEqual(bucketFill([["T", "T", "R", "T"], ["R", "T", "R", "T"], ["R", "T", "R", "T"], ["T", "T", "T", "T"]], [0, 3], "Y"), [["Y", "Y", "R", "Y"], ["R", "Y", "R", "Y"], ["R", "Y", "R", "Y"], ["Y", "Y", "Y", "Y"]]);
bucketFill([["G", "B", "G", "B"], ["R", "B", "B", "G"], ["B", "G", "B", "R"], ["B", "G", "G", "B"]], [2, 2], "G") should return [["G", "G", "G", "B"], ["R", "G", "G", "G"], ["B", "G", "G", "R"], ["B", "G", "G", "B"]].
assert.deepEqual(bucketFill([["G", "B", "G", "B"], ["R", "B", "B", "G"], ["B", "G", "B", "R"], ["B", "G", "G", "B"]], [2, 2], "G"), [["G", "G", "G", "B"], ["R", "G", "G", "G"], ["B", "G", "G", "R"], ["B", "G", "G", "B"]]);
--seed--
--seed-contents--
function bucketFill(grid, [row, col], newValue) {
return grid;
}
--solutions--
function bucketFill(grid, [row, col], newValue) {
const target = grid[row][col];
if (target === newValue) return grid;
function fill(r, c) {
if (r < 0 || r >= grid.length) return;
if (c < 0 || c >= grid[0].length) return;
if (grid[r][c] !== target) return;
grid[r][c] = newValue;
fill(r - 1, c);
fill(r + 1, c);
fill(r, c - 1);
fill(r, c + 1);
}
fill(row, col);
return grid;
}