Graph Theory37 sections · 1633 units
Open in Course

LeetCode 733 Flood Fill - Strategy

DFS or BFS?

You can use either DFS or BFS here. The logic is simple: check the color of the starting pixel (call it oldColor). If oldColor equals newColor, do nothing to avoid infinite loops.

Otherwise change the starting pixel to newColor. Look at the 44 neighbors (up, down, left, right). If a neighbor has oldColor, recursively apply the same steps to it.

The recursion stops when you hit the grid boundary or a pixel with a different color. This is DFS in action on a grid.