Number of Islands Problem Statement

You are provided with a 2-dimensional matrix having N rows and M columns, containing only 1s (land) and 0s (water). Your goal is to determine the number of islands in this matrix. An island is comprised of connected groups of 1s. A connection between cells exists in all eight possible directions: two vertically, two horizontally, and four diagonally.

Input:

The first line contains two integers N and M, representing the number of rows and columns, respectively, in the matrix.
Each of the next N lines contains M integers separated by spaces, depicting matrix values.

Output:

The output consists of a single integer which is the number of islands found in the matrix.

Example:

Input:
4 5
1 0 0 1 0
1 0 1 0 0
0 0 0 0 0
1 0 1 0 1
Output:
5

Constraints:

  • 1 <= N <= 10^3
  • 1 <= M <= 10^3
  • 0 <= ARR[i][j] <= 1
  • Time limit: 1 second.

Note:

No need for explicit printing; just implement the function and provide the correct output.

AnswerBot
4mo

Count the number of islands in a 2D matrix of 1s and 0s.

  • Iterate through the matrix and perform depth-first search (DFS) to find connected 1s.

  • Mark visited cells to avoid redundant calculations.

  • Incremen...read more

Help your peers!
Select
Add answer anonymously...

HCLTech Software Developer interview questions & answers

A Software Developer was asked 1w agoQ. What is a function in C?
A Software Developer was asked 1w agoQ. What is a dangling pointer?
A Software Developer was asked 2mo agoQ. What are the different types of joins in SQL, and how do they work?

Popular interview questions of Software Developer

A Software Developer was asked 4d agoQ1. Explain different data types in C.
A Software Developer was asked 4d agoQ2. What is a function in C?
A Software Developer was asked 4d agoQ3. What is the difference between const char* p and char const* p?
HCLTech Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits