How to print number of islands in a given matrix using C#?

An island in a matrix is a group of connected cells containing '1' (representing land) that are surrounded by '0' (representing water). Two cells are considered connected if they are adjacent horizontally or vertically. This problem uses Depth-First Search (DFS) to traverse and mark all connected land cells as visited.

The algorithm performs a linear scan of the 2D grid. When it finds a '1' that hasn't been visited, it triggers a DFS to explore the entire connected island and marks all cells in that island as visited. Each DFS call represents one complete island.

Algorithm Steps

  • Scan the matrix: Iterate through each cell in the grid.

  • Find unvisited land: When a '1' is found that hasn't been visited, increment the island count.

  • Explore the island: Use DFS to visit all connected '1' cells and mark them as visited.

  • Continue scanning: Move to the next cell and repeat until the entire matrix is processed.

Island Detection Example Input Matrix 1 1 0 1 1 0 0 0 0 0 0 1 Islands Identified 1 1 0 2 1 0 0 0 0 0 0 3 Island 1 (3 cells) Island 2 (1 cell) Island 3 (1 cell) Total Islands: 3

Implementation

using System;

namespace ConsoleApplication {
    public class Matrix {
        public int PrintNumberOfIslands(char[,] grid) {
            bool[,] visited = new bool[grid.GetLength(0), grid.GetLength(1)];
            int res = 0;
            
            for (int i = 0; i < grid.GetLength(0); i++) {
                for (int j = 0; j < grid.GetLength(1); j++) {
                    if (grid[i, j] == '1' && !visited[i, j]) {
                        DFS(grid, visited, i, j);
                        res++;
                    }
                }
            }
            return res;
        }
        
        public void DFS(char[,] grid, bool[,] visited, int i, int j) {
            if (i < 0 || i >= grid.GetLength(0)) return;
            if (j < 0 || j >= grid.GetLength(1)) return;
            if (grid[i, j] != '1' || visited[i, j]) return;
            
            visited[i, j] = true;
            
            // Explore all 4 directions
            DFS(grid, visited, i + 1, j); // Down
            DFS(grid, visited, i - 1, j); // Up
            DFS(grid, visited, i, j + 1); // Right
            DFS(grid, visited, i, j - 1); // Left
        }
    }
    
    class Program {
        static void Main(string[] args) {
            Matrix m = new Matrix();
            char[,] grid = { 
                { '1', '1', '1', '1', '0' }, 
                { '1', '1', '0', '1', '0' }, 
                { '1', '1', '0', '0', '0' }, 
                { '0', '0', '0', '0', '1' } 
            };
            
            Console.WriteLine("Number of islands: " + m.PrintNumberOfIslands(grid));
        }
    }
}

The output of the above code is −

Number of islands: 2

How It Works

The algorithm uses a visited boolean matrix to track which cells have been explored. When an unvisited '1' is found, the DFS method recursively explores all connected '1' cells in four directions (up, down, left, right) and marks them as visited. This ensures each connected component (island) is counted only once.

Time Complexity: O(m × n) where m and n are the dimensions of the matrix.

Space Complexity: O(m × n) for the visited matrix plus O(m × n) for the recursion stack in the worst case.

Alternative Example with Different Grid

using System;

class Program {
    public static int CountIslands(char[,] grid) {
        int rows = grid.GetLength(0);
        int cols = grid.GetLength(1);
        bool[,] visited = new bool[rows, cols];
        int islandCount = 0;
        
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (grid[i, j] == '1' && !visited[i, j]) {
                    ExploreIsland(grid, visited, i, j);
                    islandCount++;
                }
            }
        }
        return islandCount;
    }
    
    private static void ExploreIsland(char[,] grid, bool[,] visited, int row, int col) {
        if (row < 0 || row >= grid.GetLength(0) || 
            col < 0 || col >= grid.GetLength(1) ||
            grid[row, col] == '0' || visited[row, col]) {
            return;
        }
        
        visited[row, col] = true;
        
        ExploreIsland(grid, visited, row - 1, col);
        ExploreIsland(grid, visited, row + 1, col);
        ExploreIsland(grid, visited, row, col - 1);
        ExploreIsland(grid, visited, row, col + 1);
    }
    
    static void Main() {
        char[,] grid = {
            { '1', '0', '0', '1' },
            { '0', '0', '1', '1' },
            { '0', '1', '1', '0' },
            { '1', '0', '0', '1' }
        };
        
        Console.WriteLine("Islands found: " + CountIslands(grid));
    }
}

The output of the above code is −

Islands found: 4

Conclusion

The island counting problem demonstrates effective use of

Updated on: 2026-03-17T07:04:36+05:30

786 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements