Watch a scan find each piece of unclaimed land and a depth-first search claim its whole island, with the code lit line by line, and see why cells touching only at a corner make separate islands (LeetCode 200). O(R × C) time and space.
About this algorithm
Number of Islands counts the groups of land in a grid of 1s (land) and 0s (water), where land cells join up, down, left or right. It scans the grid cell by cell, and each time the scan lands on land no island owns yet, that is a new island: a depth-first search claims all of it before the scan moves on. This is LeetCode 200, and it runs in O(R × C) time.
Use this scan-and-flood pattern whenever a grid splits into connected regions and you need to count them, size them or treat each one as a whole: Max Area of Island, Surrounded Regions, counting enclosed regions or blobs in an image. A breadth-first flood works just as well as the depth-first one here, because only which cells belong to an island matters, not the order they are reached in. The grid DFS page searches from one start to one target; this one has no target and runs a fresh search from every island it finds.
Walk the grid from the top-left cell, row by row. Water and land already claimed are skipped.
Add one to the count, write the island's number into the cell to claim it, and put the cell on a stack.
Pop a cell and look right, down, left and up. Every unclaimed land neighbour is claimed at once and pushed. Claiming at push time means no cell is ever pushed twice.
When the stack runs dry, every cell of this island carries its number. The scan carries on from where it stopped. When the scan reaches the last cell, the count is the answer.
The map has 20 land cells. The scan finds island 1 at row 0, column 0 (counting from 0) and claims 4 cells, then island 2 at row 0, column 6, 3 cells. Island 3 starts at row 2, column 3 and winds down to the bottom-right corner, 9 cells. Island 4 is a single cell at row 2, column 7, and island 5 starts at row 3, column 0, 3 cells. The answer is 5. By eye the map shows only 3 patches, because island 1 touches island 3 at a corner and island 2 touches island 4 at a corner. A corner is not up, down, left or right, so those are separate islands.
Marking a cell only when it is popped lets two neighbours push the same cell twice, which wastes work and, if the count is per cell, gets the size wrong. Writing the island number in as the cell is pushed, as the listing does, makes the grid its own visited mark.
Time: the scan reads every cell once, and each land cell is pushed once and checks 4 neighbours. Space: one island's stack can hold a large share of the grid; the grid itself serves as the visited marks.