Number of Islands

Graphs, problem 3 of 8

Number of Islands

Medium

LC #200

griddfsconnected components

Not attempted yet

A map is a grid of "1" (land) and "0" (water). An island is a group of land cells connected up, down, left or right (not diagonally). Everything outside the grid is water. Return the number of islands.

Example 1

Input: grid = [["1","1","0","0"],
               ["1","0","0","1"],
               ["0","0","1","1"]]
Output: 2

Example 2

Input: grid = [["1","0","1"],
               ["0","1","0"],
               ["1","0","1"]]
Output: 5

Diagonal neighbours don't join islands.

Constraints

  • 1 <= rows, cols <= 200
  • grid[r][c] is "0" or "1"
  • Big islands are tested: a recursive DFS may exceed Python's recursion limit.

Python

Loading draft…

Test results

8 tests available

No results yet

Run tests your code against the examples; Submit runs the hidden tests too.

2 examples, 6 hidden

Run examples, then submit all tests.