94. Count the islands
A map is a grid of cells: 1 for land, 0 for water. An island is a group of land cells joined up, down, left or right; land cells that only touch at a corner belong to different islands. The water around the edge of the map is not shown, so land on the edge is still part of an island.
Write a function count_islands(grid) that takes the map as a list of rows and returns how many islands it has.
- An island can be any shape, winding around, with water inside it.
- A map with no land has 0 islands.
When you find a land cell you haven't seen, it starts a new island: then visit every land cell joined to it, so that none of that island is counted again.
Example 1
grid = [[1, 1, 0],
[0, 1, 0],
[0, 0, 1]]2Example 2
grid = [[1, 0, 1],
[0, 1, 0],
[1, 0, 1]]5Example 3
grid = [[1, 0, 1],
[1, 0, 1],
[1, 1, 1]]1Constraints
gridhas 1 to 20 rows of 1 to 20 cells each, all rows the same length; every cell is 0 or 1.
Submit also runs 8 more tests you can't see.
- Go through every cell. A land cell not seen yet is the start of a new island: count it, then mark its whole island as seen.
- To mark the island, keep a stack of cells to explore, starting with that cell. Pop a cell, and push each of its four neighbours that is on the map, is land and isn't seen yet. That is a depth-first search.
- A set of
(row, column)pairs works for "seen". Joining only to the cells above and to the left, row by row, isn't enough: in example 3 the arms only meet at the bottom.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def count_islands(grid):
"""Count the islands of land on the map.
grid: list of rows of 1 (land) and 0 (water)
Returns: int, how many groups of land cells are
joined up, down, left or right
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.