InferenceAI

Enter at least two characters to search.

Start free

Count Islands

mediumGraphs25 min25 XP

grid is a list of rows of 1 (land) and 0 (water). Cells connect horizontally and vertically. Return the number of islands (connected groups of land).

Requirements

  • Visit each cell at most once (O(rows×cols)O(rows \times cols)).

Examples

EXAMPLE WALKTHROUGHthree islands

A guided view of the published example, not a trace of your code.

INPUT[[[1,1,0,0],[1,1,0,0],[0,0,1,0],[0,0,0,1]]]
TASKcount_islands()
EXPECTED OUTPUT3

Start with the input values shown in this example.

Example 1 of 3

Input: grid = [[1,1,0,0],[1,1,0,0],[0,0,1,0],[0,0,0,1]]

Output: 3

Explanation: three islands

Input: grid = [[1,1,1],[0,1,0],[1,1,1]]

Output: 1

Explanation: one connected island

Input: grid = [[0,0],[0,0]]

Output: 0

Explanation: all water

Hint 1

Scan the grid; when you find unvisited land, flood-fill its island with BFS or DFS and count one.

Topics

DSAGraphsPython