Algo-Sim › Grid Graphs

Number of Islands (BFS)

Medium · Grid Graphs · step through it in Java, Python and C++ on your own input

Count the islands: groups of 1s connected up, down, left or right.

Problem

Given a grid of 1 (land) and 0 (water), count the islands. An island is a group of land cells joined horizontally or vertically, and everything outside the grid is water. This version explores each island with BFS.

Constraints

Edge cases to test

Follow-up questions

What if land is added one cell at a time?
Union-find over cells, counting merges as each cell is added (LC 305): near O(1) per addition.
Can you avoid modifying the grid?
Keep a separate visited array: O(mn) extra space.

Solution

Java

public int numIslands(char[][] grid) {
    int rows = grid.length, cols = grid[0].length, islands = 0;
    int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < cols; c++) {
            if (grid[r][c] != '1') continue;
            islands++;
            grid[r][c] = '0';
            Queue<int[]> queue = new ArrayDeque<>();
            queue.offer(new int[] { r, c });
            while (!queue.isEmpty()) {
                int[] cell = queue.poll();
                for (int[] d : dirs) {
                    int nr = cell[0] + d[0], nc = cell[1] + d[1];
                    if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] != '1') continue;
                    grid[nr][nc] = '0';
                    queue.offer(new int[] { nr, nc });
                }
            }
        }
    }
    return islands;
}

Python

from collections import deque

def num_islands(grid):
    rows, cols, islands = len(grid), len(grid[0]), 0
    dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] != "1":
                continue
            islands += 1
            grid[r][c] = "0"
            queue = deque([(r, c)])
            while queue:
                cr, cc = queue.popleft()
                for dr, dc in dirs:
                    nr, nc = cr + dr, cc + dc
                    if not (0 <= nr < rows and 0 <= nc < cols) or grid[nr][nc] != "1":
                        continue
                    grid[nr][nc] = "0"
                    queue.append((nr, nc))
    return islands

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int numIslands(vector<vector<char>> &grid) {
        int rows = int(grid.size()), cols = int(grid[0].size()), islands = 0;
        vector<vector<int>> dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                if (grid[r][c] != '1')
                    continue;
                islands++;
                grid[r][c] = '0';
                deque<vector<int>> queue = {};
                queue.push_back(vector<int>{r, c});
                while (!queue.empty()) {
                    vector<int> cell = queue.front();
                    queue.pop_front();
                    for (vector<int> &d : dirs) {
                        int nr = cell[0] + d[0], nc = cell[1] + d[1];
                        if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] != '1')
                            continue;
                        grid[nr][nc] = '0';
                        queue.push_back(vector<int>{nr, nc});
                    }
                }
            }
        }
        return islands;
    }
};

More Grid Graphs problems