Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Paint-bucket fill: recolour the 4-connected region of the start cell's colour and report how many cells changed.

Problem: Paint-bucket fill: recolour the 4-connected region of the start cell's colour and report how many cells changed.
def fill(img, r, c, new):
    old = img[r][c]
    if old == new: return 0
    cnt = 0; st = [(r, c)]
    while st:
        i, j = st.pop()
        if 0 <= i < len(img) and 0 <= j < len(img[0]) and img[i][j] == old:
            img[i][j] = new; cnt += 1
            st += [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]
    return cnt
img = [[1, 1, 0, 2], [0, 1, 1, 2], [1, 0, 1, 1], [1, 1, 0, 1]]
print(fill(img, 0, 0, 7), img[2][3], img[3][0])
What is printed?
  1. A. 7 1 1
  2. B. 6 7 1
  3. C. 7 7 1
  4. D. 10 7 7

Correct answer: C. 7 7 1

From (0, 0) the 1s reachable by up/down/left/right moves are (0,0), (0,1), (1,1), (1,2), (2,2), (2,3), (3,3) → 7 cells, so (2, 3) becomes 7. The block at (2,0), (3,0), (3,1) touches the region only diagonally, so it keeps colour 1 (all ten 1s would be counted with 8-connectivity). The old == new guard prevents an infinite loop. O(R·C).

More Coding Interview Problems questions

Exams that ask this topic