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 time and uses space.