Leetcode - Flood Fill
https://leetcode.com/problems/flood-fill/
An image
is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).
Given a coordinate (sr, sc)
representing the starting pixel (row and column) of the flood fill, and a pixel value newColor
, "flood fill" the image.
To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.
At the end, return the modified image.
Example 1:
Input: image = [[1,1,1],[1,1,0],[1,0,1]] sr = 1, sc = 1, newColor = 2 Output: [[2,2,2],[2,2,0],[2,0,1]] Explanation: From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected by a path of the same color as the starting pixel are colored with the new color. Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
func floodFill(image [][]int, sr int, sc int, newColor int) [][]int { if len(image) == 0 || len(image[0]) == 0 { return image } walk(image, sr, sc, image[sr][sc]) for i := 0; i < len(image); i++ { for j := 0; j < len(image[0]); j++ { if image[i][j] < 0 { image[i][j] = newColor } } } return image } func walk(image [][]int, i, j, color int) { if i < 0 || j < 0 || i >= len(image) || j >= len(image[0]) { return } if image[i][j] < 0 { return } directions := [][]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} if image[i][j] == color { image[i][j] = -1 for _, d := range directions { newX := i + d[0] newY := j + d[1] walk(image, newX, newY, color) } } }