Graph Theory37 sections · 1633 units
Open in Course

LeetCode 733 Flood Fill - Implementation

Coding the Solution

Here is the solution:

function dfs(image, r, c, oldColor, newColor):
    if r < 0 or r >= rows or c < 0 or c >= cols:
        return
    if image[r][c] != oldColor:
        return

    image[r][c] = newColor

    dfs(image, r + 1, c, oldColor, newColor)
    dfs(image, r - 1, c, oldColor, newColor)
    dfs(image, r, c + 1, oldColor, newColor)
    dfs(image, r, c - 1, oldColor, newColor)

function floodFill(image, sr, sc, newColor):
    oldColor = image[sr][sc]
    if oldColor != newColor:
        dfs(image, sr, sc, oldColor, newColor)
    return image

This runs in O(m×n)O(m \times n) time and uses O(m×n)O(m \times n) space.