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?- A. 7 1 1
- B. 6 7 1
- C. 7 7 1
- 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
- Problem: Rearrange a string so no two adjacent letters are equal ("" if impossible). Greedy: always place the most frequent remaining…
- Problem: A 'closed island' is a group of 0-cells (land) connected 4-directionally that does NOT touch the grid border. Count them. python…
- Problem: On a board of 'X' and 'O', capture every 'O' region not connected to the border by turning it into 'X'. Mark border-connected…
- Problem: Run Bellman–Ford from node 0 on a directed graph with negative edges, then check for a negative cycle with one more relaxation…
- Problem: All-pairs shortest paths with Floyd–Warshall on a 4-node directed graph (INF = no path). python INF = float("inf") def floyd(n…
- Problem: n computers and a list of cables; you may unplug any cable and reconnect it between any two computers. Minimum moves to connect…