Flood fill from (0, 0), which holds 1. Every cell reachable through same-valued neighbours turns into 2. A queue holds the frontier: pop a cell, paint it, push its matching neighbours. Painting on push is what keeps a cell from being queued twice.
Flood filling from row 0 column 0 with breadth-first search.
Pop (0, 0). 2 neighbours still land: (1, 0), (0, 1). Paint and queue them.
Cell 0, 0 is painted. 2 neighbours join the queue.
Pop (1, 0). 1 neighbour still land: (2, 0). Paint and queue them.
Cell 1, 0 is painted. 1 neighbours join the queue.
Pop (0, 1). No unpainted neighbour with the old colour, so nothing joins the queue.
Cell 0, 1 is painted. 0 neighbours join the queue.
Pop (2, 0). 1 neighbour still land: (2, 1). Paint and queue them.
Cell 2, 0 is painted. 1 neighbours join the queue.
Pop (2, 1). 1 neighbour still land: (2, 2). Paint and queue them.
Cell 2, 1 is painted. 1 neighbours join the queue.
Pop (2, 2). 2 neighbours still land: (3, 2), (2, 3). Paint and queue them.
Cell 2, 2 is painted. 2 neighbours join the queue.
Pop (3, 2). No unpainted neighbour with the old colour, so nothing joins the queue.
Cell 3, 2 is painted. 0 neighbours join the queue.
Pop (2, 3). 1 neighbour still land: (1, 3). Paint and queue them.
Cell 2, 3 is painted. 1 neighbours join the queue.
Pop (1, 3). No unpainted neighbour with the old colour, so nothing joins the queue.
Cell 1, 3 is painted. 0 neighbours join the queue.
The queue is empty: nothing reachable is left. 9 cells painted.
The queue is empty. 9 cells were painted.
9 cells painted. Each cell was popped once and looked at its four neighbours: O(cells). Depth-first would paint the same region in a different order.
9 cells were painted.