Search and backtracking · 13 / 15 Exercise Hard

Count islands

Objective

Create a Python program that counts the islands of a map and computes the size of the largest. An island is a group of land cells (1) connected horizontally or vertically, surrounded by water (0) or by the edge.

Instructions

  • Read an integer n (1 to 8) and then n rows of text made only of 0 and 1, all with the same length.
  • Go through all the cells. Each time you find unvisited land, it is a new island: explore it with a recursive function that visits its four neighbors and returns how many cells it has (store the visited ones in a set).
  • Show Islands: k and Largest island: t (0 if there is no land).
Input
4
1100
1001
0011
0001
Output
Islands: 2
Largest island: 4

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise