Dashboard
#42. Number of IslandsMediumGraphs

Given a 2D grid grid where '1' represents land and '0' represents water, count and return the number of islands.

An island is formed by connecting adjacent lands horizontally or vertically and is surrounded by water. You may assume water is surrounding the grid (i.e., all the edges are water).

Example 1:

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

Example 2:

Input: grid = [
    ["1","1","0","0","1"],
    ["1","1","0","0","1"],
    ["0","0","1","0","0"],
    ["0","0","0","1","1"]
  ]
Output: 4

Constraints:

  • 1 <= grid.length, grid[i].length <= 100
  • grid[i][j] is '0' or '1'.
Examples
Example 1:
Input: grid = [ ["0","1","1","1","0"], ["0","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ]
Output: 1
Example 2:
Input: grid = [ ["1","1","0","0","1"], ["1","1","0","0","1"], ["0","0","1","0","0"], ["0","0","0","1","1"] ]
Output: 4
Constraints
  • `1 <= grid.length, grid[i].length <= 100`
  • `grid[i][j]` is `'0'` or `'1'`.
Company Frequency
Amazon23Snap16Google14Zoho9PayPal9Salesforce9Tesla8Samsung8
Prerequisites
  • Matrix DFS(Data Structures & Algorithms for Beginners)
  • Matrix BFS(Data Structures & Algorithms for Beginners)
Target: O(N) time • O(1) spaceArray / Depth-First Search / Breadth-First Search / Union Find / Matrix
Socratic AI Tutor
Gemini 3.8 Flash
Loading editor...

Click "Run" or press Ctrl+Enter to execute test cases.