Educatifu
Open menu

Number of Islands

Hardgraphsgrid

A grid of 0s (water) and 1s (land) is given. An island is a group of 1s connected horizontally or vertically (not diagonally). Count the islands.

Input

Line 1: two integers r and c (rows and columns). The next r lines each contain a string of c characters, each 0 or 1.

Output

The number of islands.

Examples

Example 1

Input
3 3
110
010
001
Output
2

The top-left L-shape is one island; the lone 1 at the corner is another → 2.

Example 2

Input
1 1
1
Output
1

A single land cell.

Example 3

Input
2 2
00
00
Output
0

All water — no islands.

Constraints

  • 1 <= r, c <= 300
  • Each grid character is 0 or 1.

Hints

Reveal hint 1

Scan the grid; when you find a 1 you have not visited yet, you have found a new island.

Reveal hint 2

From that cell, flood-fill (BFS or DFS) to every connected 1 and mark them visited so you count the island only once.

Reference solution (spoiler — try it yourself first)

Approach

Iterate every cell; on an unvisited 1, increment the count and flood-fill (BFS) all 4-directionally connected land, marking it visited.

import sys
from collections import deque
data = [l for l in sys.stdin.read().split('\n')]
r, c = map(int, data[0].split())
grid = [data[1 + i] for i in range(r)]
seen = [[False] * c for _ in range(r)]
islands = 0
for i in range(r):
    for j in range(c):
        if grid[i][j] == '1' and not seen[i][j]:
            islands += 1
            q = deque([(i, j)])
            seen[i][j] = True
            while q:
                x, y = q.popleft()
                for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                    nx, ny = x + dx, y + dy
                    if 0 <= nx < r and 0 <= ny < c and grid[nx][ny] == '1' and not seen[nx][ny]:
                        seen[nx][ny] = True
                        q.append((nx, ny))
print(islands)

← All practice problems

Bring us the problem, not a perfect specification

Tell us what needs to change, who it affects and any important deadline. We will review the context and reply with useful next questions.

  1. 01Share contextDescribe the workflow, constraint or risk.
  2. 02Clarify togetherWe identify missing facts and useful options.
  3. 03Choose a startAgree a focused assessment or delivery step.
Start a conversation