Given an n × m grid[][] consisting of 'L' (land) and 'W' (water), we need to count the total number of islands present in the grid without modifying the original grid. An island is defined as a group of connected 'L' cells that are adjacent horizontally, vertically, or diagonally, and surrounded by water or the boundary of the grid.
[Approach 1] Using DFS and Additional Matrix - O(n*m) Time and O(n*m) Space
The main idea is to explore each land cell ('L') using DFS and mark all connected land cells that belong to the same island. To avoid modifying the original grid, we maintain a separate visited matrix that keeps track of which cells have already been explored. The DFS explores all 8 possible directions (up, down, left, right, and 4 diagonals), marking every connected 'L' cell as visited. This ensures that all parts of the current island are counted once. Each time we encounter an unvisited land cell, it represents the start of a new island, and we perform DFS to mark all cells of that island. By the end, the total count represents the number of distinct islands in the grid.
C++
//Driver Code Starts#include<iostream>#include<vector>usingnamespacestd;//Driver Code Ends// Checks if the given cell (r, c) can be visitedboolisSafe(vector<vector<char>>&grid,intr,intc,vector<vector<bool>>&visited){intn=grid.size();intm=grid[0].size();// Cell is within bounds, contains land ('L'), and is not yet visitedreturn(r>=0&&r<n&&c>=0&&c<m&&grid[r][c]=='L'&&!visited[r][c]);}// Performs DFS to mark all connected land cellsvoiddfs(vector<vector<char>>&grid,intr,intc,vector<vector<bool>>&visited){// Mark current cell as visitedvisited[r][c]=true;// All 8 possible directions (vertical, horizontal, diagonal)vector<int>dr={-1,-1,-1,0,0,1,1,1};vector<int>dc={-1,0,1,-1,1,-1,0,1};// Explore all connected neighboursfor(intk=0;k<8;k++){intnr=r+dr[k];intnc=c+dc[k];if(isSafe(grid,nr,nc,visited))dfs(grid,nr,nc,visited);}}// finding number of distinct islands in the gridintcountIslands(vector<vector<char>>&grid){intn=grid.size();intm=grid[0].size();// Matrix to track visited cellsvector<vector<bool>>visited(n,vector<bool>(m,false));intislands=0;// Traverse every cell in the gridfor(inti=0;i<n;i++){for(intj=0;j<m;j++){// Start a new DFS when an unvisited land cell is foundif(grid[i][j]=='L'&&!visited[i][j]){dfs(grid,i,j,visited);islands++;}}}returnislands;}//Driver Code Startsintmain(){vector<vector<char>>grid={{'L','W','W','W','W'},{'W','L','W','W','L'},{'L','W','W','L','L'},{'W','W','W','W','W'},{'L','W','L','L','W'}};// printing the number of islandscout<<countIslands(grid)<<endl;return0;}//Driver Code Ends
Java
//Driver Code Startsimportjava.util.*;publicclassMain{//Driver Code Ends// Checks if the given cell (r, c) can be visitedstaticbooleanisSafe(char[][]grid,intr,intc,boolean[][]visited){intn=grid.length;intm=grid[0].length;// Cell is within bounds, contains land ('L'), and is not yet visitedreturn(r>=0&&r<n&&c>=0&&c<m&&grid[r][c]=='L'&&!visited[r][c]);}// Performs DFS to mark all connected land cellsstaticvoiddfs(char[][]grid,intr,intc,boolean[][]visited){// Mark current cell as visitedvisited[r][c]=true;// All 8 possible directions (vertical, horizontal, diagonal)int[]dr={-1,-1,-1,0,0,1,1,1};int[]dc={-1,0,1,-1,1,-1,0,1};// Explore all connected neighboursfor(intk=0;k<8;k++){intnr=r+dr[k];intnc=c+dc[k];if(isSafe(grid,nr,nc,visited))dfs(grid,nr,nc,visited);}}// finding number of distinct islands in the gridstaticintcountIslands(char[][]grid){intn=grid.length;intm=grid[0].length;// Matrix to track visited cellsboolean[][]visited=newboolean[n][m];intislands=0;// Traverse every cell in the gridfor(inti=0;i<n;i++){for(intj=0;j<m;j++){// Start a new DFS when an unvisited land cell is foundif(grid[i][j]=='L'&&!visited[i][j]){dfs(grid,i,j,visited);islands++;}}}returnislands;}//Driver Code Startspublicstaticvoidmain(String[]args){char[][]grid={{'L','W','W','W','W'},{'W','L','W','W','L'},{'L','W','W','L','L'},{'W','W','W','W','W'},{'L','W','L','L','W'}};// printing the number of islandsSystem.out.println(countIslands(grid));}}//Driver Code Ends
Python
# Checks if the given cell (r, c) can be visiteddefisSafe(grid,r,c,visited):n=len(grid)m=len(grid[0])# Cell is within bounds, contains land ('L'), and is not yet visitedreturn(0<=r<nand0<=c<mandgrid[r][c]=='L'andnotvisited[r][c])# Performs DFS to mark all connected land cellsdefdfs(grid,r,c,visited):# Mark current cell as visitedvisited[r][c]=True# All 8 possible directions (vertical, horizontal, diagonal)dr=[-1,-1,-1,0,0,1,1,1]dc=[-1,0,1,-1,1,-1,0,1]# Explore all connected neighboursforkinrange(8):nr=r+dr[k]nc=c+dc[k]ifisSafe(grid,nr,nc,visited):dfs(grid,nr,nc,visited)# finding number of distinct islands in the griddefcountIslands(grid):n=len(grid)m=len(grid[0])# Matrix to track visited cellsvisited=[[Falsefor_inrange(m)]for_inrange(n)]islands=0# Traverse every cell in the gridforiinrange(n):forjinrange(m):# Start a new DFS when an unvisited land cell is foundifgrid[i][j]=='L'andnotvisited[i][j]:dfs(grid,i,j,visited)islands+=1returnislands#Driver Code Startsif__name__=="__main__":grid=[['L','W','W','W','W'],['W','L','W','W','L'],['L','W','W','L','L'],['W','W','W','W','W'],['L','W','L','L','W']]# printing the number of islandsprint(countIslands(grid))#Driver Code Ends
C#
//Driver Code StartsusingSystem;usingSystem.Collections.Generic;classProgram{//Driver Code Ends// Checks if the given cell (r, c) can be visitedstaticboolIsSafe(char[][]grid,intr,intc,bool[][]visited){intn=grid.Length;intm=grid[0].Length;// Cell is within bounds, contains land ('L'), and is not yet visitedreturn(r>=0&&r<n&&c>=0&&c<m&&grid[r][c]=='L'&&!visited[r][c]);}// Performs DFS to mark all connected land cellsstaticvoidDfs(char[][]grid,intr,intc,bool[][]visited){// Mark current cell as visitedvisited[r][c]=true;// All 8 possible directions (vertical, horizontal, diagonal)int[]dr={-1,-1,-1,0,0,1,1,1};int[]dc={-1,0,1,-1,1,-1,0,1};// Explore all connected neighboursfor(intk=0;k<8;k++){intnr=r+dr[k];intnc=c+dc[k];if(IsSafe(grid,nr,nc,visited))Dfs(grid,nr,nc,visited);}}// finding number of distinct islands in the gridstaticintCountIslands(char[][]grid){intn=grid.Length;intm=grid[0].Length;// Matrix to track visited cellsbool[][]visited=newbool[n][];for(inti=0;i<n;i++)visited[i]=newbool[m];intislands=0;// Traverse every cell in the gridfor(inti=0;i<n;i++){for(intj=0;j<m;j++){// Start a new DFS when an unvisited land cell is foundif(grid[i][j]=='L'&&!visited[i][j]){Dfs(grid,i,j,visited);islands++;}}}returnislands;}//Driver Code StartsstaticvoidMain(){char[][]grid=newchar[][]{newchar[]{'L','W','W','W','W'},newchar[]{'W','L','W','W','L'},newchar[]{'L','W','W','L','L'},newchar[]{'W','W','W','W','W'},newchar[]{'L','W','L','L','W'}};// printing the number of islandsConsole.WriteLine(CountIslands(grid));}}//Driver Code Ends
JavaScript
// Checks if the given cell (r, c) can be visitedfunctionisSafe(grid,r,c,visited){constn=grid.length;constm=grid[0].length;// Cell is within bounds, contains land ('L'), and is not yet visitedreturn(r>=0&&r<n&&c>=0&&c<m&&grid[r][c]==='L'&&!visited[r][c]);}// Performs DFS to mark all connected land cellsfunctiondfs(grid,r,c,visited){// Mark current cell as visitedvisited[r][c]=true;// All 8 possible directions (vertical, horizontal, diagonal)constdr=[-1,-1,-1,0,0,1,1,1];constdc=[-1,0,1,-1,1,-1,0,1];// Explore all connected neighboursfor(letk=0;k<8;k++){constnr=r+dr[k];constnc=c+dc[k];if(isSafe(grid,nr,nc,visited))dfs(grid,nr,nc,visited);}}// finding number of distinct islands in the gridfunctioncountIslands(grid){constn=grid.length;constm=grid[0].length;// Matrix to track visited cellsconstvisited=Array.from({length:n},()=>Array(m).fill(false));letislands=0;// Traverse every cell in the gridfor(leti=0;i<n;i++){for(letj=0;j<m;j++){// Start a new DFS when an unvisited land cell is foundif(grid[i][j]==='L'&&!visited[i][j]){dfs(grid,i,j,visited);islands++;}}}returnislands;}//Driver Code Startsconstgrid=[['L','W','W','W','W'],['W','L','W','W','L'],['L','W','W','L','L'],['W','W','W','W','W'],['L','W','L','L','W']];// printing the number of islandsconsole.log(countIslands(grid));//Driver Code Ends
Output
4
[Approach 2]Using Breadth First Search - O(n*m) time and O(n*m) space
The idea is to use Breadth First Search(BFS) to explore all connected land cells for each island. We traverse the entire grid, and whenever we encounter an unvisited land cell ('L'), we perform a BFS starting from that cell to explore its entire connected component. During BFS, we visit all cells connected horizontally, vertically, or diagonally to the current land cell. To ensure we don’t revisit the same cell multiple times, we maintain a separate boolean matrix to mark visited cells instead of modifying the original grid. Each BFS traversal explores one complete island, after which we increment the island counter. Repeating this for all cells ensures that every island is counted exactly once, and the final counter gives the total number of islands in the grid.
C++
//Driver Code Starts#include<iostream>#include<vector>#include<queue>usingnamespacestd;//Driver Code Ends// Check if the cell (r, c) is valid for BFS traversal// It must lie within grid bounds, contain land ('L'), and not be visited yetboolisSafe(vector<vector<char>>&grid,intr,intc,vector<vector<bool>>&visited){intn=grid.size();intm=grid[0].size();return(r>=0&&r<n&&c>=0&&c<m&&grid[r][c]=='L'&&!visited[r][c]);}// Perform BFS to traverse all connected land cells (forming one island)voidbfs(vector<vector<char>>&grid,vector<vector<bool>>&visited,intstartR,intstartC){// Possible 8 directions (vertical, horizontal, and diagonal)vector<int>dRow={-1,-1,-1,0,0,1,1,1};vector<int>dCol={-1,0,1,-1,1,-1,0,1};queue<pair<int,int>>q;q.push({startR,startC});visited[startR][startC]=true;// Explore all reachable land cells for this islandwhile(!q.empty()){auto[r,c]=q.front();q.pop();// Check all 8 neighbors of the current cellfor(intk=0;k<8;k++){intnewR=r+dRow[k];intnewC=c+dCol[k];if(isSafe(grid,newR,newC,visited)){visited[newR][newC]=true;q.push({newR,newC});}}}}// Count the total number of islands in the gridintcountIslands(vector<vector<char>>&grid){intn=grid.size();intm=grid[0].size();vector<vector<bool>>visited(n,vector<bool>(m,false));intislandCount=0;// Traverse every cell in the gridfor(intr=0;r<n;r++){for(intc=0;c<m;c++){// If an unvisited land cell is found, start BFS for that islandif(grid[r][c]=='L'&&!visited[r][c]){bfs(grid,visited,r,c);islandCount++;}}}returnislandCount;}//Driver Code Startsintmain(){vector<vector<char>>grid={{'L','L','W','W','W'},{'W','L','W','W','L'},{'L','W','W','L','L'},{'W','W','W','W','W'},{'L','W','L','L','W'}};cout<<countIslands(grid)<<endl;return0;}//Driver Code Ends
Java
//Driver Code Startsimportjava.util.*;publicclassMain{//Driver Code Ends// Check if the cell (r, c) is valid for BFS traversal// It must lie within grid bounds, contain land ('L'), and not be visited yetstaticbooleanisSafe(char[][]grid,intr,intc,boolean[][]visited){intn=grid.length;intm=grid[0].length;return(r>=0&&r<n&&c>=0&&c<m&&grid[r][c]=='L'&&!visited[r][c]);}// Perform BFS to traverse all connected land cells (forming one island)staticvoidbfs(char[][]grid,boolean[][]visited,intstartR,intstartC){// Possible 8 directions (vertical, horizontal, and diagonal)int[]dRow={-1,-1,-1,0,0,1,1,1};int[]dCol={-1,0,1,-1,1,-1,0,1};Queue<int[]>q=newLinkedList<>();q.add(newint[]{startR,startC});visited[startR][startC]=true;// Explore all reachable land cells for this islandwhile(!q.isEmpty()){int[]cell=q.poll();intr=cell[0];intc=cell[1];// Check all 8 neighbors of the current cellfor(intk=0;k<8;k++){intnewR=r+dRow[k];intnewC=c+dCol[k];if(isSafe(grid,newR,newC,visited)){visited[newR][newC]=true;q.add(newint[]{newR,newC});}}}}// Count the total number of islands in the gridstaticintcountIslands(char[][]grid){intn=grid.length;intm=grid[0].length;boolean[][]visited=newboolean[n][m];intislandCount=0;// Traverse every cell in the gridfor(intr=0;r<n;r++){for(intc=0;c<m;c++){// If an unvisited land cell is found, start BFS for that islandif(grid[r][c]=='L'&&!visited[r][c]){bfs(grid,visited,r,c);islandCount++;}}}returnislandCount;}//Driver Code Startspublicstaticvoidmain(String[]args){char[][]grid={{'L','L','W','W','W'},{'W','L','W','W','L'},{'L','W','W','L','L'},{'W','W','W','W','W'},{'L','W','L','L','W'}};System.out.println(countIslands(grid));}}//Driver Code Ends
Python
#Driver Code Startsfromcollectionsimportdeque#Driver Code Ends# Check if the cell (r, c) is valid for BFS traversal# It must lie within grid bounds, contain land ('L'), and not be visited yetdefisSafe(grid,r,c,visited):n=len(grid)m=len(grid[0])return(0<=r<nand0<=c<mandgrid[r][c]=='L'andnotvisited[r][c])# Perform BFS to traverse all connected land cells (forming one island)defbfs(grid,visited,startR,startC):# Possible 8 directions (vertical, horizontal, and diagonal)dRow=[-1,-1,-1,0,0,1,1,1]dCol=[-1,0,1,-1,1,-1,0,1]q=deque()q.append((startR,startC))visited[startR][startC]=True# Explore all reachable land cells for this islandwhileq:r,c=q.popleft()# Check all 8 neighbors of the current cellforkinrange(8):newR=r+dRow[k]newC=c+dCol[k]ifisSafe(grid,newR,newC,visited):visited[newR][newC]=Trueq.append((newR,newC))# Count the total number of islands in the griddefcountIslands(grid):n=len(grid)m=len(grid[0])visited=[[False]*mfor_inrange(n)]islandCount=0# Traverse every cell in the gridforrinrange(n):forcinrange(m):# If an unvisited land cell is found, start BFS for that islandifgrid[r][c]=='L'andnotvisited[r][c]:bfs(grid,visited,r,c)islandCount+=1returnislandCount#Driver Code Startsif__name__=="__main__":grid=[['L','L','W','W','W'],['W','L','W','W','L'],['L','W','W','L','L'],['W','W','W','W','W'],['L','W','L','L','W']]print(countIslands(grid))#Driver Code Ends
C#
//Driver Code StartsusingSystem;usingSystem.Collections.Generic;classProgram{//Driver Code Ends// Check if the cell (r, c) is valid for BFS traversal// It must lie within grid bounds, contain land ('L'), and not be visited yetstaticboolIsSafe(char[][]grid,intr,intc,bool[][]visited){intn=grid.Length;intm=grid[0].Length;return(r>=0&&r<n&&c>=0&&c<m&&grid[r][c]=='L'&&!visited[r][c]);}// Perform BFS to traverse all connected land cells (forming one island)staticvoidBfs(char[][]grid,bool[][]visited,intstartR,intstartC){// Possible 8 directions (vertical, horizontal, and diagonal)int[]dRow={-1,-1,-1,0,0,1,1,1};int[]dCol={-1,0,1,-1,1,-1,0,1};Queue<(int,int)>q=newQueue<(int,int)>();q.Enqueue((startR,startC));visited[startR][startC]=true;// Explore all reachable land cells for this islandwhile(q.Count>0){var(r,c)=q.Dequeue();// Check all 8 neighbors of the current cellfor(intk=0;k<8;k++){intnewR=r+dRow[k];intnewC=c+dCol[k];if(IsSafe(grid,newR,newC,visited)){visited[newR][newC]=true;q.Enqueue((newR,newC));}}}}// Count the total number of islands in the gridstaticintCountIslands(char[][]grid){intn=grid.Length;intm=grid[0].Length;bool[][]visited=newbool[n][];for(inti=0;i<n;i++)visited[i]=newbool[m];intislandCount=0;// Traverse every cell in the gridfor(intr=0;r<n;r++){for(intc=0;c<m;c++){// If an unvisited land cell is found, start BFS for that islandif(grid[r][c]=='L'&&!visited[r][c]){Bfs(grid,visited,r,c);islandCount++;}}}returnislandCount;}//Driver Code StartsstaticvoidMain(){char[][]grid=newchar[][]{newchar[]{'L','L','W','W','W'},newchar[]{'W','L','W','W','L'},newchar[]{'L','W','W','L','L'},newchar[]{'W','W','W','W','W'},newchar[]{'L','W','L','L','W'}};Console.WriteLine(CountIslands(grid));}}//Driver Code Ends
JavaScript
// Check if the cell (r, c) is valid for BFS traversal// It must lie within grid bounds, contain land ('L'), and not be visited yetfunctionisSafe(grid,r,c,visited){constn=grid.length;constm=grid[0].length;return(r>=0&&r<n&&c>=0&&c<m&&grid[r][c]==='L'&&!visited[r][c]);}// Perform BFS to traverse all connected land cells (forming one island)functionbfs(grid,visited,startR,startC){// Possible 8 directions (vertical, horizontal, and diagonal)constdRow=[-1,-1,-1,0,0,1,1,1];constdCol=[-1,0,1,-1,1,-1,0,1];constq=[];q.push([startR,startC]);visited[startR][startC]=true;// Explore all reachable land cells for this islandwhile(q.length>0){const[r,c]=q.shift();// Check all 8 neighbors of the current cellfor(letk=0;k<8;k++){constnewR=r+dRow[k];constnewC=c+dCol[k];if(isSafe(grid,newR,newC,visited)){visited[newR][newC]=true;q.push([newR,newC]);}}}}// Count the total number of islands in the gridfunctioncountIslands(grid){constn=grid.length;constm=grid[0].length;constvisited=Array.from({length:n},()=>Array(m).fill(false));letislandCount=0;// Traverse every cell in the gridfor(letr=0;r<n;r++){for(letc=0;c<m;c++){// If an unvisited land cell is found, start BFS for that islandif(grid[r][c]==='L'&&!visited[r][c]){bfs(grid,visited,r,c);islandCount++;}}}returnislandCount;}//Driver Code Startsconstgrid=[['L','L','W','W','W'],['W','L','W','W','L'],['L','W','W','L','L'],['W','W','W','W','W'],['L','W','L','L','W']];console.log(countIslands(grid));//Driver Code Ends
Output
4
[Approach 3] Using Disjoint Set - O(n*m) time and O(n*m) space
The idea is to model the grid as a graph where each land cell acts as a node. Using the Disjoint Set (Union-Find) structure, we initially treat every land cell as its own parent. Then, for each land cell, we check all eight neighboring directions — if a neighbor is also land, we perform a union operation to merge their sets. After all unions are done, each unique parent in the Disjoint Set represents one distinct island. Counting these unique parents gives the total number of islands in the grid.
C++
//Driver Code Starts#include<iostream>#include<vector>#include<unordered_set>usingnamespacestd;//Driver Code Ends// Disjoint Set Union (Union-Find) classclassDisjointSet{vector<int>parent,rank;public:// Initialize DSU with each node as its own parentDisjointSet(intn){parent.resize(n);rank.assign(n,0);for(inti=0;i<n;i++)parent[i]=i;}// Find operation with path compressionintfind(intx){if(parent[x]!=x)parent[x]=find(parent[x]);returnparent[x];}// Union operation by rankvoidunite(intx,inty){intxRoot=find(x);intyRoot=find(y);if(xRoot==yRoot)return;if(rank[xRoot]<rank[yRoot])parent[xRoot]=yRoot;elseif(rank[yRoot]<rank[xRoot])parent[yRoot]=xRoot;else{parent[yRoot]=xRoot;rank[xRoot]++;}}};// Count total islands in the grid using DSUintcountIslands(vector<vector<char>>&grid){intn=grid.size();intm=grid[0].size();DisjointSetds(n*m);// Directions for 8-connected neighborsvector<pair<int,int>>directions={{-1,0},{1,0},{0,-1},{0,1},{-1,-1},{-1,1},{1,-1},{1,1}};autogetIndex=[&](intr,intc){returnr*m+c;};// Perform union for all connected 'L' (land) cellsfor(intr=0;r<n;r++){for(intc=0;c<m;c++){if(grid[r][c]=='L'){for(auto[dr,dc]:directions){intnr=r+dr,nc=c+dc;if(nr>=0&&nr<n&&nc>=0&&nc<m&&grid[nr][nc]=='L')ds.unite(getIndex(r,c),getIndex(nr,nc));}}}}// Use a set to count unique root parents representing islandsunordered_set<int>uniqueIslands;for(intr=0;r<n;r++){for(intc=0;c<m;c++){if(grid[r][c]=='L')uniqueIslands.insert(ds.find(getIndex(r,c)));}}returnuniqueIslands.size();}//Driver Code Startsintmain(){vector<vector<char>>grid={{'L','L','W','W','W'},{'W','L','W','W','L'},{'L','W','W','L','L'},{'W','W','W','W','W'},{'L','W','L','L','W'}};cout<<countIslands(grid)<<endl;return0;}//Driver Code Ends
Java
//Driver Code Startsimportjava.util.*;//Driver Code EndsclassDisjointSet{privateint[]parent;privateint[]rank;// Initialize DSU with each node as its own parentpublicDisjointSet(intn){parent=newint[n];rank=newint[n];for(inti=0;i<n;i++)parent[i]=i;}// Find operation with path compressionpublicintfind(intx){if(parent[x]!=x)parent[x]=find(parent[x]);returnparent[x];}// Union operation by rankpublicvoidunite(intx,inty){intxRoot=find(x);intyRoot=find(y);if(xRoot==yRoot)return;if(rank[xRoot]<rank[yRoot])parent[xRoot]=yRoot;elseif(rank[yRoot]<rank[xRoot])parent[yRoot]=xRoot;else{parent[yRoot]=xRoot;rank[xRoot]++;}}}// Count total islands in the grid using DSUpublicclassMain{publicstaticintcountIslands(char[][]grid){intn=grid.length;intm=grid[0].length;DisjointSetds=newDisjointSet(n*m);// Directions for 8-connected neighborsint[][]directions={{-1,0},{1,0},{0,-1},{0,1},{-1,-1},{-1,1},{1,-1},{1,1}};// Perform union for all connected 'L' (land) cellsfor(intr=0;r<n;r++){for(intc=0;c<m;c++){if(grid[r][c]=='L'){for(int[]dir:directions){intnr=r+dir[0],nc=c+dir[1];if(nr>=0&&nr<n&&nc>=0&&nc<m&&grid[nr][nc]=='L')ds.unite(r*m+c,nr*m+nc);}}}}// Use a set to count unique root parents// representing islandsSet<Integer>uniqueIslands=newHashSet<>();for(intr=0;r<n;r++){for(intc=0;c<m;c++){if(grid[r][c]=='L')uniqueIslands.add(ds.find(r*m+c));}}returnuniqueIslands.size();}//Driver Code Startspublicstaticvoidmain(String[]args){char[][]grid={{'L','L','W','W','W'},{'W','L','W','W','L'},{'L','W','W','L','L'},{'W','W','W','W','W'},{'L','W','L','L','W'}};System.out.println(countIslands(grid));}}//Driver Code Ends
Python
classDisjointSet:# Initialize DSU with each node as its own parentdef__init__(self,n):self.parent=list(range(n))self.rank=[0]*n# Find operation with path compressiondeffind(self,x):ifself.parent[x]!=x:self.parent[x]=self.find(self.parent[x])returnself.parent[x]# Union operation by rankdefunite(self,x,y):xRoot=self.find(x)yRoot=self.find(y)ifxRoot==yRoot:returnifself.rank[xRoot]<self.rank[yRoot]:self.parent[xRoot]=yRootelifself.rank[yRoot]<self.rank[xRoot]:self.parent[yRoot]=xRootelse:self.parent[yRoot]=xRootself.rank[xRoot]+=1defcountIslands(grid):n=len(grid)m=len(grid[0])ds=DisjointSet(n*m)# Directions for 8-connected neighborsdirections=[(-1,0),(1,0),(0,-1),(0,1),(-1,-1),(-1,1),(1,-1),(1,1)]# Perform union for all connected 'L' (land) cellsforrinrange(n):forcinrange(m):ifgrid[r][c]=='L':fordr,dcindirections:nr,nc=r+dr,c+dcif0<=nr<nand0<=nc<mandgrid[nr][nc]=='L':ds.unite(r*m+c,nr*m+nc)# Use a set to count unique root parents representing islandsuniqueIslands=set()forrinrange(n):forcinrange(m):ifgrid[r][c]=='L':uniqueIslands.add(ds.find(r*m+c))returnlen(uniqueIslands)#Driver Code Startsif__name__=="__main__":grid=[['L','L','W','W','W'],['W','L','W','W','L'],['L','W','W','L','L'],['W','W','W','W','W'],['L','W','L','L','W']]print(countIslands(grid))#Driver Code Ends
C#
//Driver Code StartsusingSystem;usingSystem.Collections.Generic;//Driver Code EndsclassDisjointSet{privateint[]parent;privateint[]rank;// Initialize DSU with each node as its own parentpublicDisjointSet(intn){parent=newint[n];rank=newint[n];for(inti=0;i<n;i++)parent[i]=i;}// Find operation with path compressionpublicintFind(intx){if(parent[x]!=x)parent[x]=Find(parent[x]);returnparent[x];}// Union operation by rankpublicvoidUnite(intx,inty){intxRoot=Find(x);intyRoot=Find(y);if(xRoot==yRoot)return;if(rank[xRoot]<rank[yRoot])parent[xRoot]=yRoot;elseif(rank[yRoot]<rank[xRoot])parent[yRoot]=xRoot;else{parent[yRoot]=xRoot;rank[xRoot]++;}}}classProgram{// Count total islands in the grid using DSUstaticintCountIslands(char[][]grid){intn=grid.Length;intm=grid[0].Length;DisjointSetds=newDisjointSet(n*m);// Directions for 8-connected neighborsint[][]directions={newint[]{-1,0},newint[]{1,0},newint[]{0,-1},newint[]{0,1},newint[]{-1,-1},newint[]{-1,1},newint[]{1,-1},newint[]{1,1}};// Perform union for all connected 'L' (land) cellsfor(intr=0;r<n;r++){for(intc=0;c<m;c++){if(grid[r][c]=='L'){foreach(vardirindirections){intnr=r+dir[0],nc=c+dir[1];if(nr>=0&&nr<n&&nc>=0&&nc<m&&grid[nr][nc]=='L')ds.Unite(r*m+c,nr*m+nc);}}}}// Use a set to count unique root parents// representing islandsHashSet<int>uniqueIslands=newHashSet<int>();for(intr=0;r<n;r++){for(intc=0;c<m;c++){if(grid[r][c]=='L')uniqueIslands.Add(ds.Find(r*m+c));}}returnuniqueIslands.Count;}//Driver Code StartsstaticvoidMain(){char[][]grid={newchar[]{'L','L','W','W','W'},newchar[]{'W','L','W','W','L'},newchar[]{'L','W','W','L','L'},newchar[]{'W','W','W','W','W'},newchar[]{'L','W','L','L','W'}};Console.WriteLine(CountIslands(grid));}}//Driver Code Ends
JavaScript
classDisjointSet{constructor(n){this.parent=Array.from({length:n},(_,i)=>i);this.rank=newArray(n).fill(0);}// Find operation with path compressionfind(x){if(this.parent[x]!==x)this.parent[x]=this.find(this.parent[x]);returnthis.parent[x];}// Union operation by rankunite(x,y){letxRoot=this.find(x);letyRoot=this.find(y);if(xRoot===yRoot)return;if(this.rank[xRoot]<this.rank[yRoot]){this.parent[xRoot]=yRoot;}elseif(this.rank[yRoot]<this.rank[xRoot]){this.parent[yRoot]=xRoot;}else{this.parent[yRoot]=xRoot;this.rank[xRoot]++;}}}// Count total islands in the grid using DSUfunctioncountIslands(grid){letn=grid.length;letm=grid[0].length;letds=newDisjointSet(n*m);// Directions for 8-connected neighborsletdirections=[[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]];// Perform union for all connected 'L' (land) cellsfor(letr=0;r<n;r++){for(letc=0;c<m;c++){if(grid[r][c]==="L"){for(let[dr,dc]ofdirections){letnr=r+dr,nc=c+dc;if(nr>=0&&nr<n&&nc>=0&&nc<m&&grid[nr][nc]==="L")ds.unite(r*m+c,nr*m+nc);}}}}// Use a set to count unique root parents representing// islandsletuniqueIslands=newSet();for(letr=0;r<n;r++){for(letc=0;c<m;c++){if(grid[r][c]==="L")uniqueIslands.add(ds.find(r*m+c));}}returnuniqueIslands.size;}//Driver Code Starts// Example usageletgrid=[["L","L","W","W","W"],["W","L","W","W","L"],["L","W","W","L","L"],["W","W","W","W","W"],["L","W","L","L","W"]];console.log(countIslands(grid));//Driver Code Ends