Flood Fill

LeetCode 733 · View on LeetCode

DFS from the starting pixel, changing every connected pixel with the same original color to the new color.

package main

import "fmt"

func floodFill(image [][]int, sr, sc, color int) [][]int {
	original := image[sr][sc]
	if original == color {
		return image // avoid infinite loop
	}

	var dfs func(r, c int)
	dfs = func(r, c int) {
		if r < 0 || r >= len(image) || c < 0 || c >= len(image[0]) {
			return
		}
		if image[r][c] != original {
			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
}

func main() {
	image := [][]int{
		{1, 1, 1},
		{1, 1, 0},
		{1, 0, 1},
	}
	result := floodFill(image, 1, 1, 2)
	fmt.Println(result) // [[2 2 2] [2 2 0] [2 0 1]]
}
▶ Open Go Playground

Copy the code above and paste to run

© 2026 ByteLearn.dev. Free courses for developers. · Privacy