Overview
Given an m × n image grid, a starting pixel (sr, sc), and a new color, perform a flood fill: change the starting pixel and all connected pixels with the same original color to the new color. Connected means sharing an edge (up, down, left, right).
Constraints
1 <= m, n <= 500 <= image[i][j], color <= 655350 <= sr < m, 0 <= sc < n
Examples
floodFill([[1,1,1],[1,1,0],[1,0,1]], 1, 1, 2); // => [[2,2,2],[2,2,0],[2,0,1]]
Solution
Reveal solution
function floodFill(image, sr, sc, color) {
const orig = image[sr][sc];
if (orig === color) return image;
const m = image.length, n = image[0].length;
function dfs(r, c) {
if (r < 0 || r >= m || c < 0 || c >= n) return;
if (image[r][c] !== orig) return;
image[r][c] = color;
dfs(r+1,c); dfs(r-1,c); dfs(r,c+1); dfs(r,c-1);
}
dfs(sr, sc);
return image;
}Resources
flood-fill.js
Flood Fill
easycodingAlgorithmsBFS
Overview
Given an m × n image grid, a starting pixel (sr, sc), and a new color, perform a flood fill: change the starting pixel and all connected pixels with the same original color to the new color. Connected means sharing an edge (up, down, left, right).
Constraints
1 <= m, n <= 500 <= image[i][j], color <= 655350 <= sr < m, 0 <= sc < n
Examples
floodFill([[1,1,1],[1,1,0],[1,0,1]], 1, 1, 2); // => [[2,2,2],[2,2,0],[2,0,1]]
Solution
Reveal solution
function floodFill(image, sr, sc, color) {
const orig = image[sr][sc];
if (orig === color) return image;
const m = image.length, n = image[0].length;
function dfs(r, c) {
if (r < 0 || r >= m || c < 0 || c >= n) return;
if (image[r][c] !== orig) return;
image[r][c] = color;
dfs(r+1,c); dfs(r-1,c); dfs(r,c+1); dfs(r,c-1);
}
dfs(sr, sc);
return image;
}Resources
NameTopicDifficulty
103 of 103 problems