Implement the floodFillChangedCount method that returns how many cells are changed during flood fill.

The input contains an image represented as a 2D integer matrix. sr and sc are the starting row and column, and color is the new color to apply.

Your task is to perform flood fill from the starting cell and return how many cells were changed. Only cells connected up, down, left, or right with the original starting color should be changed.

If the starting cell already has the new color, no cell needs to change and the answer is 0.

Example 1

Input
image (int[][]) = [[1,1,1],[1,1,0],[1,0,1]]
rows (int) = 3
cols (int) = 3
sr (int) = 1
sc (int) = 1
color (int) = 2
Returns (int) 6

Example 2

Input
image (int[][]) = [[0,0,0],[0,0,0]]
rows (int) = 2
cols (int) = 3
sr (int) = 0
sc (int) = 0
color (int) = 1
Returns (int) 6

Example 3

Input
image (int[][]) = [[1,1],[1,1]]
rows (int) = 2
cols (int) = 2
sr (int) = 0
sc (int) = 0
color (int) = 1
Returns (int) 0

First remember the original color at image[sr][sc].

Use DFS or BFS from the starting cell. Visit only valid neighbouring cells that have the same original color. Change each visited cell to the new color and increase the changed count.

Do not move diagonally, and do not visit cells with a different color.

Pseudocode:

function floodFillChangedCount(image, rows, cols, sr, sc, color):
    originalColor = image[sr][sc]
    if originalColor == color:
        return 0
    changed = 0
    queue = empty queue
    push [sr, sc] into queue
    while queue is not empty:
        row, col = remove front from queue
        if row or col is outside the image:
            continue
        if image[row][col] != originalColor:
            continue
        image[row][col] = color
        changed++
        push [row - 1, col] into queue
        push [row + 1, col] into queue
        push [row, col - 1] into queue
        push [row, col + 1] into queue
    return changed
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.