Skip to main content

Connected Region Counter

easy
GraphDepth First SearchMatrixFloodfillDfs Recursive
Asked atAmazonGoogleMicrosoftBloomberg

Problem Description

You are given a 2D grid of characters where `'L'` represents land and `'W'` represents water.

Two land cells are part of the same **island** if they are adjacent horizontally or vertically.

Return the total number of distinct islands in the grid.

**Example 1:**
```
Input: grid = [
["L","L","W","W"],
["L","W","W","L"],
["W","W","L","L"]
]
Output: 3
Explanation: Top-left cluster, top-right single cell, and bottom-right cluster are three separate islands.
```

**Example 2:**
```
Input: grid = [
["W","W","W"],
["W","W","W"]
]
Output: 0
Explanation: No land cells exist.
```

Constraints

  • 1 <= grid.length <= 300
  • 1 <= grid[0].length <= 300
  • grid[i][j] is either 'L' or 'W'

Follow-up

Can you solve this problem without modifying the input grid, using O(1) extra space beyond the recursion stack?

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.