Dsa
Matrix
Medium
Number of Islands in a Grid
Given a 2D grid consisting of '1's (land) and '0's (water), write a function that counts the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Input Format:
- The first line contains two integers m (rows) and n (columns) of the grid.
- The next m lines each contain a string of n characters ('0' or '1').
Output Format:
- A single integer representing the number of islands.
Example:
Input:
4 5
11000
11000
00100
00011
Output:
3
Key concepts
matrixdfsgraph
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now