Skip to main content

Command Palette

Search for a command to run...

count islands

Published
1 min readView as Markdown
public class Solution {
    public int numIslands(char[][] grid) {
        int rows = grid.length;
        int cols = grid[0].length;

        int islandCount = 0;

        // Traverse every cell in the grid
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                // If land is found
                if (grid[r][c] == '1') {
                    islandCount++;
                    markIsland(grid, r, c, rows, cols);
                }
            }
        }

        return islandCount;
    }

    // Mark all connected land as visited using DFS
    private void markIsland(char[][] grid, int r, int c, int rows, int cols) {
        // Base case: check for boundaries and water
        if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] == '0') {
            return;
        }
        // Mark current land cell as visited
        grid[r][c] = '0';
        // Explore in all 4 directions
        markIsland(grid, r + 1, c, rows, cols); // Down
        markIsland(grid, r - 1, c, rows, cols); // Up
        markIsland(grid, r, c + 1, rows, cols); // Right
        markIsland(grid, r, c - 1, rows, cols); // Left
    }
}

More from this blog

Amit singh's blog

235 posts