You get a grid of '1' (land) and '0' (water). An island is a group of land cells joined up, down, left or right; cells that touch only at a corner are not joined. Count the islands.
Example: in the grid with rows 11000, 10011 and 00101 there are 3 islands: three cells in the top-left corner, three on the right, and the single cell in the middle of the bottom row, which touches the right-hand island only at a corner.
Note
The cells are the characters '1' and '0', not numbers. A test against the number 1 finds no land, and the count comes out 0.
Try it yourself first: LeetCode 200 ↗. Then step through the solution below.
Without marking the land already seen, every land cell would start a search of its own, and an island would be found again from each of its cells. With L land cells that is up to L searches of up to L cells, O(L2), plus a way to tell which results are the same island.
The clue is in the words "joined up, down, left or right": a group of joined cells is found by a search from any one of its cells. Scan the grid cell by cell. The first time the scan meets land, that land belongs to an island not counted yet: count it, then visit the whole island from there and mark every one of its cells.
The helper sink does the visiting with breadth-first search: a queue of cells to look at, each one checking its four neighbours and adding the land among them. A cell is marked when it goes into the queue, not when it comes out: otherwise a cell reached from two neighbours would go in twice. Marked cells read as water to the scan, so no island is counted twice.
Note
sink could also be a recursive depth-first search: call it on each land neighbour instead of queueing it. The count is the same, but a large island makes the calls go deep, and in Python an island of about a thousand cells in a row hits the recursion limit. The queue has no such limit.
The player runs the code on the example. Press → for each step: the lines it runs light up in the code.
On a phone, Full screen keeps the picture and the code on one screen.
from collections import deque def num_islands(grid): count = 0 for r in range(len(grid)): for c in range(len(grid[0])): if grid[r][c] == '1': count += 1 sink(grid, r, c) return count def sink(grid, r, c): grid[r][c] = '0' queue = deque([(r, c)]) while queue: i, j = queue.popleft() for y, x in ((i+1, j), (i-1, j), (i, j+1), (i, j-1)): if 0 <= y < len(grid) and 0 <= x < len(grid[0]) and grid[y][x] == '1': grid[y][x] = '0' queue.append((y, x))
Now write it yourself on LeetCode 200 ↗, or go on: Course Schedule →
grid has 3 rows and 5 columns: 1 is land, 0 is water. How many islands are there?count starts at 0: it counts the islands found.r and c go through grid row by row. Cell (0, 0) is land, the first of an island.count goes up by 1, to 1.sink turns the whole island into water. It writes 0 into this cell and queues it. The corner number is its island.i, j. The queue holds the cells whose neighbours are still to be looked at.y, x goes through its four neighbours: the first that is unmarked land is (1, 0).count goes up by 1, to 2.sink turns this island into water too: it writes 0 into the cell and queues it.count goes up by 1, to 3.sink turns this island into water too: it writes 0 into the cell and queues it.Note
The code has two functions. num_islands scans the grid row by row and counts the islands. sink turns one island into water, starting from one of its cells, so that the scan never counts it again.
| Approach | Time | Space |
|---|---|---|
| Brute force: a fresh search from every land cell, each with its own marks | O(L2) | O(L) |
| Depth-first search, recursive | O(rows × cols) | O(rows × cols) |
| Union-find over the land cells | O(rows × cols), almost | O(rows × cols) |
| Breadth-first search with a queue this page | O(rows × cols) | O(rows × cols) |
L is the number of land cells.
10 over 01: diagonal neighbours are not checked, so these are 2 islands.The blocks below are steps of Number of Islands in words, and two of them do not belong. Put the right ones in order and check: your algorithm runs on the example grid, so a mistake shows in its answer. Once it is right, the code appears beside your blocks.
Click the blocks in the order they run, or drag them into the lines.Tap the blocks in the order they run. Two of them don't belong. Each block keeps its indent: it runs inside the nearest line above it that ends in a colon.
Your algorithm
Blocks
Now write it yourself on LeetCode 200 ↗, or go on: Course Schedule →
from collections import deque def num_islands(grid): count = 0 for r in range(len(grid)): for c in range(len(grid[0])): if grid[r][c] == '1': count += 1 sink(grid, r, c) return count def sink(grid, r, c): grid[r][c] = '0' queue = deque([(r, c)]) while queue: i, j = queue.popleft() for y, x in ((i+1, j), (i-1, j), (i, j+1), (i, j-1)): if 0 <= y < len(grid) and 0 <= x < len(grid[0]) and grid[y][x] == '1': grid[y][x] = '0' queue.append((y, x))Can you do it without changing the grid? Keep the visited cells in a set (or a second grid of booleans) instead of overwriting them with '0'. The scan and the search stay the same; the price is O(rows × cols) extra space for the marks.
What if land is added one cell at a time, with the count after each? A new search after every cell costs O(rows × cols) each time. With union-find, a new cell adds one island, and each join with a neighbouring island takes one away: almost O(1) per cell.
LeetCode is a trademark of LeetCode LLC. VisiGrab is not affiliated with LeetCode or with Blind; the problems are told in our own words, with our own examples.