3.1 KiB
id, title, challengeType, dashedName
| id | title | challengeType | dashedName |
|---|---|---|---|
| 6a1d9f98e819ed70a0e994db | Challenge 329: Bucket Fill | 29 | 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--
bucket_fill([["R", "G"], ["R", "G"]], [0, 1], "B") should return [["R", "B"], ["R", "B"]].
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(bucket_fill([["R", "G"], ["R", "G"]], [0, 1], "B"), [["R", "B"], ["R", "B"]])`)
}})
bucket_fill([["Y", "G", "G"], ["Y", "Y", "Y"], ["B", "Y", "R"]], [1, 2], "B") should return [["B", "G", "G"], ["B", "B", "B"], ["B", "B", "R"]].
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(bucket_fill([["Y", "G", "G"], ["Y", "Y", "Y"], ["B", "Y", "R"]], [1, 2], "B"), [["B", "G", "G"], ["B", "B", "B"], ["B", "B", "R"]])`)
}})
bucket_fill([["O", "O", "P"], ["P", "O", "O"], ["P", "P", "O"]], [2, 0], "R") should return [["O", "O", "P"], ["R", "O", "O"], ["R", "R", "O"]].
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(bucket_fill([["O", "O", "P"], ["P", "O", "O"], ["P", "P", "O"]], [2, 0], "R"), [["O", "O", "P"], ["R", "O", "O"], ["R", "R", "O"]])`)
}})
bucket_fill([["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"]].
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(bucket_fill([["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"]])`)
}})
bucket_fill([["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"]].
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(bucket_fill([["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--
def bucket_fill(grid, pos, new_value):
return grid
--solutions--
def bucket_fill(grid, pos, new_value):
row, col = pos
target = grid[row][col]
if target == new_value:
return grid
def fill(r, c):
if r < 0 or r >= len(grid):
return
if c < 0 or c >= len(grid[0]):
return
if grid[r][c] != target:
return
grid[r][c] = new_value
fill(r - 1, c)
fill(r + 1, c)
fill(r, c - 1)
fill(r, c + 1)
fill(row, col)
return grid