DFS
Time O(rows × cols) Space O(rows × cols)Remember the original colour; DFS recolouring cells that still have it.
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int color) {
int old = image[sr][sc];
if (old != color) fill(image, sr, sc, old, color);
return image;
}
private void fill(int[][] img, int r, int c, int old, int color) {
if (r < 0 || c < 0 || r >= img.length || c >= img[0].length || img[r][c] != old) return;
img[r][c] = color;
fill(img, r + 1, c, old, color); fill(img, r - 1, c, old, color);
fill(img, r, c + 1, old, color); fill(img, r, c - 1, old, color);
}
}Verdict: The recoloured cell acts as its own visited mark.