Canvas With Bucket Fill and Undo
Implement a class Canvas, a grid of rows by cols cells that all start with color 0. Rows are numbered from 0 at the top and columns from 0 at the left. Write these methods:
Canvas(rows, cols)makes the grid.paint(r, c, color)sets cell(r, c)tocolorand returns the color it had before.fill(r, c, color)givescolorto cell(r, c)and to every cell connected to it by steps up, down, left or right through cells of the same color as(r, c). Returns how many cells changed.undo()takes back the most recentpaintorfillthat has not been undone yet, restoring every cell it changed. Returnstrue, orfalseif there is nothing to undo. Apaintorfillthat changed no cell does not count, soundoskips it.color_at(r, c)returns the color of cell(r, c).count_color(color)returns how many cells havecolor.
r and c are always on the grid. The tests call the methods in sequence and compare every return value. The expected list holds null for the constructor.
Example 1
Canvas(3, 4)
paint(0, 1, 1) returns 0
paint(1, 1, 1) returns 0
paint(2, 1, 1) returns 0
fill(0, 3, 5) returns 6
count_color(0) returns 3
color_at(2, 2) returns 5
undo() returns true
count_color(5) returns 0
The three painted cells form a wall down column 1, so the fill from (0, 3) colors only the 6 cells to its right. Column 0 keeps color 0, and undo takes the whole fill back.
Constraints
1 <= rows, cols <= 60 <= color <= 5- Each test makes
1to40method calls after the constructor.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.