Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training

140. Number of Islands

MediumDay 42 of 60Graphs

You are given an m x n grid where "1" is land and "0" is water. An island is a group of land cells connected horizontally or vertically (not diagonally), and the grid is surrounded by water on all sides. Return the number of islands.

Example 1
Input: grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
Output: 1
All land cells are connected into one island.
Example 2
Input: grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
Output: 3
Constraints
  • 1 <= m, n <= 300
  • grid[i][j] is "0" or "1"
Hints
Frequently asked at: Amazon, Microsoft, Google, Meta, Bloomberg, Goldman Sachs
Ctrl + Enter runs the examples

Not sure what to learn next?

A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

  1. 1Discuss your goals
  2. 2Get a personal plan
  3. 3Start learning
Book for β‚Ή200/ 30 min