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:
- 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:
C++
#include <bits/stdc++.h>
using namespace std;
vector<pair< int , int > > directions
= { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
void dfs(vector<vector< char > >& worldMap, int row, int col,
int rows, int cols)
{
worldMap[row][col] = 'W' ;
for ( const auto & dir : directions) {
int new_row = (row + dir.first + rows) % rows;
int new_col = (col + dir.second + cols) % cols;
if (worldMap[new_row][new_col] == 'L' ) {
dfs(worldMap, new_row, new_col, rows, cols);
}
}
}
int countIslandsOnMap(vector<vector< char > >& worldMap)
{
int rows = worldMap.size();
int cols = worldMap[0].size();
int islands = 0;
for ( int i = 0; i < rows; i++) {
for ( int j = 0; j < cols; j++) {
if (worldMap[i][j] == 'L' ) {
islands++;
dfs(worldMap, i, j, rows, cols);
}
}
}
return islands;
}
int main()
{
vector<vector< char > > worldMap
= { { 'L' , 'W' , 'W' , 'L' },
{ 'L' , 'W' , 'W' , 'L' },
{ 'L' , 'W' , 'W' , 'L' },
{ 'L' , 'W' , 'W' , 'L' } };
cout << countIslandsOnMap(worldMap) << endl;
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.List;
public class IslandCounter {
static List< int []> directions = List.of( new int []{- 1 , 0 },
new int []{ 1 , 0 }, new int []{ 0 , - 1 }, new int []{ 0 , 1 });
public static void main(String[] args) {
char [][] worldMap = {
{ 'L' , 'W' , 'W' , 'L' },
{ 'L' , 'W' , 'W' , 'L' },
{ 'L' , 'W' , 'W' , 'L' },
{ 'L' , 'W' , 'W' , 'L' }
};
int rows = worldMap.length;
int cols = worldMap[ 0 ].length;
int islands = countIslandsOnMap(worldMap, rows, cols);
System.out.println(islands);
}
public static int countIslandsOnMap( char [][] worldMap, int rows, int cols) {
int islands = 0 ;
for ( int i = 0 ; i < rows; i++) {
for ( int j = 0 ; j < cols; j++) {
if (worldMap[i][j] == 'L' ) {
islands++;
dfs(worldMap, i, j, rows, cols);
}
}
}
return islands;
}
public static void dfs( char [][] worldMap, int row, int col, int rows, int cols) {
worldMap[row][col] = 'W' ;
for ( int [] dir : directions) {
int newRow = (row + dir[ 0 ] + rows) % rows;
int newCol = (col + dir[ 1 ] + cols) % cols;
if (worldMap[newRow][newCol] == 'L' ) {
dfs(worldMap, newRow, newCol, rows, cols);
}
}
}
}
|
Python3
def countIslandsOnMap(worldMap):
rows = len (worldMap)
cols = len (worldMap[ 0 ])
islands = 0
for i in range (rows):
for j in range (cols):
if worldMap[i][j] = = 'L' :
islands + = 1
dfs(i, j, rows, cols)
return islands
def dfs(row, col, rows, cols):
worldMap[row][col] = 'W'
directions = [( - 1 , 0 ), ( 1 , 0 ), ( 0 , - 1 ), ( 0 , 1 )]
for dr, dc in directions:
new_row, new_col = (row + dr) % rows, (col + dc) % cols
if worldMap[new_row][new_col] = = 'L' :
dfs(new_row, new_col, rows, cols)
worldMap = [[ 'L' , 'W' , 'W' , 'L' ], [ 'L' , 'W' , 'W' , 'L' ],
[ 'L' , 'W' , 'W' , 'L' ], [ 'L' , 'W' , 'W' , 'L' ]]
print (countIslandsOnMap(worldMap))
|
C#
using System;
using System.Collections.Generic;
class Program
{
static List<( int , int )> directions = new List<( int , int )>
{
(-1, 0), (1, 0), (0, -1), (0, 1)
};
static void Dfs(List<List< char >> worldMap, int row, int col, int rows, int cols)
{
worldMap[row][col] = 'W' ;
foreach ( var dir in directions)
{
int newRow = (row + dir.Item1 + rows) % rows;
int newCol = (col + dir.Item2 + cols) % cols;
if (worldMap[newRow][newCol] == 'L' )
{
Dfs(worldMap, newRow, newCol, rows, cols);
}
}
}
static int CountIslandsOnMap(List<List< char >> worldMap)
{
int rows = worldMap.Count;
int cols = worldMap[0].Count;
int islands = 0;
for ( int i = 0; i < rows; i++)
{
for ( int j = 0; j < cols; j++)
{
if (worldMap[i][j] == 'L' )
{
islands++;
Dfs(worldMap, i, j, rows, cols);
}
}
}
return islands;
}
static void Main()
{
List<List< char >> worldMap = new List<List< char >>
{
new List< char >{ 'L' , 'W' , 'W' , 'L' },
new List< char >{ 'L' , 'W' , 'W' , 'L' },
new List< char >{ 'L' , 'W' , 'W' , 'L' },
new List< char >{ 'L' , 'W' , 'W' , 'L' }
};
Console.WriteLine(CountIslandsOnMap(worldMap));
}
}
|
Javascript
function countIslandsOnMap(worldMap) {
const rows = worldMap.length;
const cols = worldMap[0].length;
let islands = 0;
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (worldMap[i][j] === 'L' ) {
islands += 1;
dfs(i, j, rows, cols);
}
}
}
return islands;
}
function dfs(row, col, rows, cols) {
worldMap[row][col] = 'W' ;
let directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
for ( var i = 0; i < directions.length; i++) {
let [dr, dc] = directions[i];
const new_row = (row + dr + rows) % rows;
const new_col = (col + dc + cols) % cols;
if (worldMap[new_row][new_col] === 'L' ) {
dfs(new_row, new_col, rows, cols);
}
}
}
const worldMap = [
[ 'L' , 'W' , 'W' , 'L' ],
[ 'L' , 'W' , 'W' , 'L' ],
[ 'L' , 'W' , 'W' , 'L' ],
[ 'L' , 'W' , 'W' , 'L' ]
];
console.log(countIslandsOnMap(worldMap));
|
Time Complexity: O(N * M), where N is the number of rows and M is the number of columns Auxiliary Space: O(1)
|