Number of Islands

Medium
BFS

Given an m x n 2D binary grid which represents a map of '1's (land) and '0's (water), return 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.

This is a classic grid BFS problem where we use BFS to explore and mark all connected land cells belonging to the same island.

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
Explanation: All the 1s in the top-left are connected, forming 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
Explanation: There are three separate groups of connected 1s, forming three islands.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] is "0" or "1"
Show Hints (4)
Hint 1: Iterate through the grid. When you find a "1", start a BFS from that cell.
Hint 2: During BFS, mark all connected "1"s as visited (or change them to "0").
Hint 3: Each BFS call explores one complete island.
Hint 4: Count the number of times you initiate a BFS - this equals the number of islands.
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?