Skip to content
DeepForgeby svx
All problems
EasyGraph Algorithmsgraph-014

Number of Islands via Graph Traversal

Problem

Count the islands in a grid of string cells, where 1 is land and 0 is water.

An island is a maximal group of land cells connected horizontally or vertically (4-connectivity). Return the number of islands; an empty grid has 0.

Hint

Flood fill from every unvisited land cell and increment the counter.

Test cases

case 1
in: [[["1","1","0"],["1","0","0"],["0","0","1"]]]
expected: 2
case 2
in: [[["1","1"],["1","1"]]]
expected: 1
case 3
in: [[["0","0"],["0","0"]]]
expected: 0
case 4
in: [[]]
expected: 0
case 5
in: [[["1"]]]
expected: 1
Starter codePython
def num_islands(grid):
    # Your code here
    pass

5 test cases · run your code against them in the editor