A grid is a graph
Each square of this 4 × 5 map is land or water. Make every land square a node, and join two land squares with an edge when they share a side: up, down, left or right. That gives 10 nodes and 8 edges.
Flood fill
A connected component is a biggest group of nodes joined by paths. To find them all, the code walks the land squares in reading order. todo holds every square not yet in an island; a square still in todo starts a new one.
(0, 0) is in todo, so it starts a part. Breadth-first search spreads from it: pop a square from the queue; each neighbour still in todo is removed, added to the part and queued. 4 squares: island 1.
The scan moves on. (0, 1), (1, 0) and (1, 1) left todo during the flood, so line 4 skips them. (1, 3) is new: flood it. The queue reaches (1, 4), then (2, 4). Island 2 has 3 squares.
(1, 4) is skipped. (2, 2) touches island 1 only at a corner, and a corner is not an edge, so no flood reached it. It starts island 3: (2, 2), then (3, 2), then (3, 1).
The scan skips the last three squares, all filled already. parts now holds 3 lists, one per island, so len(parts) is 3. Every land square sits in exactly one part: 4 + 3 + 3 = 10.
Cost and neighbours
Each land square leaves todo once, so it is queued once and popped once, checking 4 neighbours: here 10 pops and 40 checks. That is O(V + E) for any graph, and O(R × C) for a whole grid of R rows and C columns.
Whether corners count is part of the problem. With 8 neighbours, diagonals are edges too: (1, 1)–(2, 2) and (2, 2)–(1, 3) link all three islands, and the count drops to 1. Only near() would change.
What happens
;; step 1/8 · grid-graph row 0 # # . . . row 1 # # . # # row 2 . . # . # row 3 . # # . . # = land (10 nodes), . = water edges (shared sides): 8 (0, 0) – (0, 1) (0, 0) – (1, 0) (0, 1) – (1, 1) (1, 0) – (1, 1) (1, 3) – (1, 4) (1, 4) – (2, 4) (2, 2) – (3, 2) (3, 1) – (3, 2) a square is (row, column), counted from 0
This is what MIT 6.006 calls Full-BFS: run a search from any unvisited node, put everything it reaches in one component, repeat until no node is left. It runs in O(|V| + |E|) time. Sedgewick and Wayne's CC.java does the same with depth-first search. near() returns squares off the map, such as (-1, 0). They are never in todo, so the code needs no bounds check.