#733

Flood Fill

Easy Grid DFS

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Starting from one pixel, repaint it and every 4-directionally connected pixel of the same original colour with a new colour.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: paint a region of same-coloured pixels.

Why this works: DFS from the start to neighbours with the original colour; painting also marks them visited.

Example: [[1,1,1],[1,1,0],[1,0,1]], start (1,1), colour 2

all 1s connected to the centre become 2the bottom-right 1 isn't connected → stays 1

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Missing the "same colour" early return, which causes infinite recursion.

Solve on LeetCode ↗
Complexity
  • Time: O(m·n).
  • Space: O(m·n) recursion in the worst case.
Topic: Graphs
🎬 Episodes 74–85: video coming soon