![]() |
VOOZH | about |
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.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:
Below is the implementation of the approach:
1
Time Complexity: O(N * M), where N is the number of rows and M is the number of columns
Auxiliary Space: O(1)