16. Number of Islands
mediumAsked at Electronic ArtsCount connected land regions in a 2D grid using BFS/DFS, a core EA interview topic tied directly to game-map analysis and connected-component detection.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
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.
Constraints
m == grid.length, n == grid[i].length1 <= m, n <= 300grid[i][j] is '0' or '1'
Examples
Example 1
grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]1Example 2
grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]3Approaches
1. DFS flood fill
For each unvisited land cell, DFS to mark all connected land as visited, incrementing island count once per DFS root.
- Time
- O(m*n)
- Space
- O(m*n)
function numIslands(grid) {
let count = 0;
function dfs(r, c) {
if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] !== '1') return;
grid[r][c] = '0';
dfs(r+1,c); dfs(r-1,c); dfs(r,c+1); dfs(r,c-1);
}
for (let r = 0; r < grid.length; r++)
for (let c = 0; c < grid[0].length; c++)
if (grid[r][c] === '1') { count++; dfs(r, c); }
return count;
}Tradeoff:
2. BFS with queue
BFS from each unvisited '1' cell using a queue, marking cells visited as they are enqueued. Preferred in EA's game-engine interviews for its iterative nature and predictable stack depth on large maps.
- Time
- O(m*n)
- Space
- O(min(m,n))
function numIslands(grid) {
const m = grid.length, n = grid[0].length;
let count = 0;
const dirs = [[1,0],[-1,0],[0,1],[0,-1]];
for (let r = 0; r < m; r++) {
for (let c = 0; c < n; c++) {
if (grid[r][c] !== '1') continue;
count++;
const q = [[r, c]];
grid[r][c] = '0';
while (q.length) {
const [cr, cc] = q.shift();
for (const [dr, dc] of dirs) {
const nr = cr+dr, nc = cc+dc;
if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] === '1') {
grid[nr][nc] = '0';
q.push([nr, nc]);
}
}
}
}
}
return count;
}Tradeoff:
Electronic Arts-specific tips
EA interviews cover game development data structures, pathfinding (A*, BFS on grids), spatial algorithms, and simulation problems. Grid/matrix manipulation and BFS on 2D arrays are very common.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Number of Islands and other Electronic Arts interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →