713595. Geeks Island

Medium

Here is a detailed Markdown blog post for the GeeksforGeeks problem "Geeks Island":

Geeks Island

Summary

The "Geeks Island" problem involves finding all connected components in a given matrix. The input matrix represents an island, where 0s represent water and 1s represent land. The task is to find all the distinct islands (connected 1s) in the matrix.

Detailed Explanation

To solve this problem, we will use Depth-First Search (DFS) algorithm. The idea is to traverse the matrix from top to bottom and left to right. When we encounter a 1, it means we have found an island, so we start exploring it by visiting all adjacent cells that are also 1s. We mark these visited cells as part of this island.

Here's a step-by-step breakdown of the solution:

  1. Initialize a matrix visited with the same dimensions as the input matrix, and set all its elements to false.
  2. Traverse the input matrix from top to bottom and left to right.
  3. When we encounter a 1 in the input matrix, it means we have found an island.
  4. Start exploring this island by visiting all adjacent cells that are also 1s (up, down, left, right).
  5. Mark these visited cells as part of this island by setting their corresponding visited elements to true.
  6. Continue this process until the entire input matrix has been traversed.

Time complexity: O(mn), where m is the number of rows and n is the number of columns in the input matrix, since we are visiting each cell once. Space complexity: O(mn) for the visited matrix.

Here's a sample ASCII art diagram to illustrate this process:

0 0 1 0
0 0 1 0
1 1 1 1
0 0 1 0

Optimized Solutions

Java

View on GeeksforGeeks
public class GeeksIsland {
    public static void findConnectedComponents(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        boolean[][] visited = new boolean[m][n];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (matrix[i][j] == 1 && !visited[i][j]) {
                    dfs(matrix, visited, i, j);
                }
            }
        }
    }

    private static void dfs(int[][] matrix, boolean[][] visited, int i, int j) {
        int[] directions = {-1, 0, 1, 0, -1};
        for (int k = 0; k < 4; k++) {
            int x = i + directions[k % 2][k / 2];
            int y = j;
            if (x >= 0 && x < matrix.length && y >= 0 && y < matrix[0].length
                    && matrix[x][y] == 1 && !visited[x][y]) {
                visited[x][y] = true;
                dfs(matrix, visited, x, y);
            }
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.