VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-of-islands-in-a-circular-matrix/

⇱ Number of Islands in a Circular Matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of Islands in a Circular Matrix

Last Updated : 23 Jul, 2025

Given a 2D Matrix world map[][] of size N * M, such that all the places covered via land are represented by ā€˜L’ and the rest by ā€˜W’. Since the world is spherical rows and columns are cyclic (before row 1 row n comes and after row n row 1 same for the column). Count the number of islands.

Examples:

Input: N = 4, M = 4, worldMap = [ ['L', 'W', 'W', 'L'] , ['L', 'W, 'W', 'L'] , ['L', 'W', 'W', 'L'] , ['L', 'W', 'W', 'L'] ]
Output: 1
Explanation: Since the map is circular, all the lands are connected to form 1 Island.

šŸ‘ Islands

Input: N = 3, M = 3, worldMap = [ ['W', 'W', 'W'] , ['W', 'L', 'W',] , ['W', 'W', 'W'] ]
Output: 1
Explanation: There is just 1 island covered by water.

Approach: The problem can be solved using the following approach:

The approach is to use DFS to count islands on a world map grid, considering the map's cyclic nature. Start from an unvisited land cell, it explores adjacent cells while cyclically wrapping around the map. Whenever we move outside the matrix, then we can simply modulo the row and column with the total number of rows and columns respectively to land inside the matrix. Instead of using another matrix to count the visited lands, we can simply change the visited land to water.

Steps to solve the problem:

  • Declare a function dfs() to start a DFS from an unvisited land cell.
  • Explore all the land cells connected with this cell.
  • While exploring a land cell, turn the land cell to water cell so that no cell is counted twice.
  • If at any point we move outside the grid, simply modulo the row and column with the total number of rows and columns respectively.
  • After the DFS gets completed, if we encounter any unvisited land cell, then increment the count of islands by 1 and again start a DFS from this cell.
  • Finally, return the number of islands.

Below is the implementation of the approach:


Output
1

Time Complexity: O(N * M), where N is the number of rows and M is the number of columns
Auxiliary Space: O(1)

Comment
Article Tags: