200. Number of Islands
Asked at 81Amazon85Bloomberg84Apple80Microsoft72Meta65Google64Anduril100Walmart Labs97TikTok96Qualcomm91Uber89ByteDance87Oracle83Waymo79LinkedIn75Nvidia74Visa72Yandex63Infosys61Goldman Sachs60Rippling54tcs36Hive100Moloco100OKX100Rivian100Snap100Splunk100Wix100Zenefits100CrowdStrike97Siemens97BitGo89Tesla88Sigmoid87Samsung86ServiceNow84eBay82Zoho81AMD79SoFi79Lucid78Whatnot78Intel76Tinkoff75Wells Fargo75Docusign74Comcast74SAP73Aon71PayPal71Adobe69Huawei67Accenture66Squarepoint Capital66Cloudflare66Expedia65Capital One64Citadel64Zomato62HashedIn62Nutanix60Autodesk59Coupang58Two Sigma58Meesho57Salesforce57Turing55PhonePe53Barclays53General Motors52Grammarly51IBM50DE Shaw47Juspay47Cisco45Intuit43Flipkart43Snowflake39Pinterest36DoorDash36
Problem
In a grid of '1' (land) and '0' (water), an island is a group of land cells connected horizontally or vertically. Count the islands; everything outside the grid is water.
Example: ["11000","11000","00100","00011"] → 3
Constraints: up to 300 × 300.
Scan the grid; each unvisited 1 starts a new island — flood-fill it (DFS/BFS) to mark the whole island visited.
1 1 0 0 0
1 1 0 0 0 -> 3 islands
0 0 1 0 0
0 0 0 1 1
Complexity: O(R·C).
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
R, C = len(grid), len(grid[0])
def sink(r, c):
st = [(r, c)]
grid[r][c] = "0"
while st:
r, c = st.pop()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == "1":
grid[nr][nc] = "0"
st.append((nr, nc))
count = 0
for r in range(R):
for c in range(C):
if grid[r][c] == "1":
count += 1
sink(r, c)
return count
g = [list(r) for r in ["11000", "11000", "00100", "00011"]]
assert Solution().numIslands(g) == 3
assert Solution().numIslands([["0"]]) == 0
assert Solution().numIslands([list(r) for r in ["11110", "11010", "11000", "00000"]]) == 1
assert Solution().numIslands([list(r) for r in ["101", "010", "101"]]) == 5
class Solution {
public int numIslands(char[][] grid) {
int count = 0;
for (int r = 0; r < grid.length; r++)
for (int c = 0; c < grid[0].length; c++)
if (grid[r][c] == '1') { count++; sink(grid, r, c); }
return count;
}
private void sink(char[][] g, int r, int c) {
if (r < 0 || c < 0 || r >= g.length || c >= g[0].length || g[r][c] != '1') return;
g[r][c] = '0';
sink(g, r + 1, c); sink(g, r - 1, c); sink(g, r, c + 1); sink(g, r, c - 1);
}
}
func numIslands(grid [][]byte) int {
R, C := len(grid), len(grid[0])
sink := func(r, c int) { // flood-fill one island with an explicit stack
st := [][2]int{{r, c}}
grid[r][c] = '0'
for len(st) > 0 {
p := st[len(st)-1]
st = st[:len(st)-1]
for _, d := range [][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} {
nr, nc := p[0]+d[0], p[1]+d[1]
if nr >= 0 && nr < R && nc >= 0 && nc < C && grid[nr][nc] == '1' {
grid[nr][nc] = '0'
st = append(st, [2]int{nr, nc})
}
}
}
}
count := 0
for r := 0; r < R; r++ {
for c := 0; c < C; c++ {
if grid[r][c] == '1' {
count++
sink(r, c)
}
}
}
return count
}