200. Number of Islands
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Graphs
- Time
- O(MN)
- Space
- O(MN)
Standard Solution (C++)
SummaryGiven a 2D grid of '1's (land) and '0's (water), count how many distinct connected groups of land cells exist, where connectivity is defined by the four cardinal directions.
Approach
- Scan every cell; when a '1' is found, increment the island counter and flood-fill the entire island to avoid recounting it.
- BFS from each unvisited land cell processes neighbors level by level and marks them visited by overwriting with '0' in-place, so no extra visited array is needed.
- The BFS queue holds at most O(min(M, N)) cells at any given time (the "wavefront" width), giving better space than the O(M*N) recursion stack of DFS in worst cases.
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int m = grid.size();
int n = grid[0].size();
int islands = 0;
// Four cardinal directions: up, down, left, right
const int dr[] = {-1, 1, 0, 0};
const int dc[] = { 0, 0, -1, 1};
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] != '1') continue;
// Found a new island — BFS to sink the entire connected land mass
++islands;
queue<pair<int,int>> q;
grid[i][j] = '0'; // mark visited before enqueuing
q.push({i, j});
while (!q.empty()) {
auto [r, c] = q.front();
q.pop();
for (int d = 0; d < 4; ++d) {
int nr = r + dr[d];
int nc = c + dc[d];
if (nr >= 0 && nr < m && nc >= 0 && nc < n
&& grid[nr][nc] == '1') {
grid[nr][nc] = '0'; // mark before enqueue to avoid duplicates
q.push({nr, nc});
}
}
}
}
}
return islands;
}
};
Time O(M * N) Space O(min(M, N))
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
#include <vector>
using namespace std;
class Solution {
public:
const int dx[4]={-1, 1, 0, 0};
const int dy[4]={0, 0, -1, 1};
void dfs(vector<vector<char>>& grid, int x, int y){
int m=grid.size();
int n=grid[0].size();
grid[x][y]='0';
for(int k=0; k<4; ++k){
int nx=x+dx[k];
int ny=y+dy[k];
if(nx>=0 && nx<m && ny>=0 && ny<n && grid[nx][ny]=='1'){
dfs(grid, nx, ny);
}
}
}
int numIslands(vector<vector<char>>& grid) {
// BFS: O(MN), O(min(M, N))
// DFS: O(MN), O(MN)
// Union Find: O(MN.alpha(MN)), O(MN)
int m=grid.size();
int n=grid[0].size();
int count=0;
for(int i=0; i<m; ++i){
for(int j=0; j<n; ++j){
if(grid[i][j]=='1'){
++count;
dfs(grid, i, j);
}
}
}
return count;
}
};
// Time Complexity: O(MN), since we visit each cell at most once.
// Space Complexity: O(MN) in the worst case (when the grid is filled with land), due to the recursion stack in DFS.
// For BFS, the space complexity would be O(min(M, N)) in the worst case Time O(MN) Space O(MN)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.