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.
Using DFS with a Visited Matrix - O(n x m) Time and O(n x m) Space
Traverse the grid and whenever an unvisited 'L' is found, treat it as a new island and use DFS to visit all land cells connected to it in 8 directions. A separate visited matrix is used so that the original grid is not modified.
Create a visited matrix.
Traverse every cell of the grid.
For each unvisited 'L', increment the island count.
Run DFS and mark all connected land cells as visited.
Check all 8 directions during DFS.
Return the total island count.
Consider the grid:
Start from (0,0). It is an unvisited 'L', so islands = 1.
DFS visits (0,1) and (1,1). These cells belong to the same island.
Continue scanning. At (1,4), we find another unvisited 'L', so islands = 2.
DFS visits (2,3) and (2,4).
At (2,0), we find an unvisited 'L', so islands = 3.
At (4,0), we find another unvisited 'L', so islands = 4.
DFS visits (4,2) and (4,3) as part of the same island.
No unvisited land cells remain.
Therefore: Number of islands = 4
C++
#include<iostream>#include<vector>usingnamespacestd;// 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;}intmain(){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'}};cout<<countIslands(grid)<<endl;return0;}
Java
classGFG{// Checks if the given cell (r, c) can be visitedpublicstaticbooleanisSafe(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 cellspublicstaticvoiddfs(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 gridpublicstaticintcountIslands(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;}publicstaticvoidmain(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'}};System.out.println(countIslands(grid));}}
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+=1returnislandsif__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))
C#
usingSystem;classGFG{// Checks if the given cell (r, c) can be visitedpublicstaticboolisSafe(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 cellspublicstaticvoiddfs(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 gridpublicstaticintcountIslands(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;}publicstaticvoidMain(){char[][]grid={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'}};Console.WriteLine(countIslands(grid));}}
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 codeconstgrid=[['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));
Output
4
Using Breadth First Search - O(n x m) time and O(n x m) space
Traverse the grid and whenever an unvisited 'L' is found, treat it as a new island and use BFS to visit all land cells connected to it in all 8 directions. A separate visited matrix is used to avoid modifying the original grid.
Create a visited matrix of size n × m.
Traverse every cell of the grid.
If an unvisited 'L' is found, increment the island count.
Add the cell to a queue and mark it as visited.
Remove a cell from the queue and check all 8 directions.
Add every valid, unvisited land cell to the queue and mark it visited.
Continue until the queue becomes empty.
Repeat for the remaining cells and return the island count.
Consider the grid:
Start BFS from (0,0) -> islands = 1; visit (0,1) and (1,1).
Start BFS from (1,4) -> islands = 2; visit (2,3) and (2,4).
Start BFS from (2,0) -> islands = 3.
Start BFS from (4,0) -> islands = 4.
The remaining connected land cells (4,2) and (4,3) are visited in the same BFS.
No unvisited land remains.
Therefore: Number of islands = 4
C++
#include<iostream>#include<vector>#include<queue>usingnamespacestd;// 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]);}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;}intmain(){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;}
Java
importjava.util.Queue;importjava.util.LinkedList;classGFG{// Check if the cell (r, c) is valid for BFS traversal// It must lie within grid bounds, contain land ('L'), and not be visited yetpublicstaticbooleanisSafe(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]);}publicstaticvoidbfs(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 gridpublicstaticintcountIslands(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;}publicstaticvoidmain(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));}}
Python
fromcollectionsimportdeque# 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])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+=1returnislandCountif__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))
C#
usingSystem;usingSystem.Collections.Generic;classGFG{// Check if the cell (r, c) is valid for BFS traversal// It must lie within grid bounds, contain land ('L'), and not be visited yetpublicstaticboolisSafe(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]);}publicstaticvoidbfs(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){varcurrent=q.Dequeue();intr=current.Item1;intc=current.Item2;// 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 gridpublicstaticintcountIslands(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;}publicstaticvoidMain(){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));}}
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]);}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;}constgrid=[['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));
Output
4
Using Disjoint Set - O(n x m) time and O(n x m) space
Model the grid as a graph where each land cell is a node. Initially, every land cell belongs to its own set. For each land cell, check all 8 directions and merge it with any connected land cell. Finally, the number of unique sets gives the number of islands.
Create a DSU structure where every cell initially has itself as its parent.
Convert each cell (r, c) into a unique index using r * m + c.
Traverse every cell of the grid.
For each land cell 'L', check all 8 neighboring cells.
If a neighboring cell is also 'L', merge both cells using unite().
After all cells are processed, find the parent of every land cell.
Store the parents in a HashSet to remove duplicates.
The size of the set is the total number of islands.
C++
#include<bits/stdc++.h>usingnamespacestd;// Find the parent of a cellintfind(intx,vector<int>&parent){if(parent[x]!=x)parent[x]=find(parent[x],parent);returnparent[x];}// Join two connected cellsvoidunite(intx,inty,vector<int>&parent,vector<int>&rank){x=find(x,parent);y=find(y,parent);if(x==y)return;if(rank[x]<rank[y])parent[x]=y;elseif(rank[x]>rank[y])parent[y]=x;else{parent[y]=x;rank[x]++;}}intcountIslands(vector<vector<char>>&grid){intn=grid.size();intm=grid[0].size();// Initially, every cell belongs to its own groupvector<int>parent(n*m);vector<int>rank(n*m,0);for(inti=0;i<n*m;i++)parent[i]=i;// 8 possible directionsintdr[]={-1,-1,-1,0,0,1,1,1};intdc[]={-1,0,1,-1,1,-1,0,1};// Join connected land cellsfor(intr=0;r<n;r++){for(intc=0;c<m;c++){if(grid[r][c]!='L')continue;intcurrent=r*m+c;for(intk=0;k<8;k++){intnr=r+dr[k];intnc=c+dc[k];if(nr>=0&&nr<n&&nc>=0&&nc<m&&grid[nr][nc]=='L'){intnext=nr*m+nc;unite(current,next,parent,rank);}}}}// Count unique island groupsunordered_set<int>islands;for(intr=0;r<n;r++){for(intc=0;c<m;c++){if(grid[r][c]=='L'){intcell=r*m+c;islands.insert(find(cell,parent));}}}returnislands.size();}intmain(){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;}
Java
importjava.util.HashSet;// Find the parent of a cellpublicstaticintfind(intx,int[]parent){if(parent[x]!=x)parent[x]=find(parent[x],parent);returnparent[x];}// Join two connected cellspublicstaticvoidunite(intx,inty,int[]parent,int[]rank){x=find(x,parent);y=find(y,parent);if(x==y)return;if(rank[x]<rank[y])parent[x]=y;elseif(rank[x]>rank[y])parent[y]=x;else{parent[y]=x;rank[x]++;}}publicstaticintcountIslands(char[][]grid){intn=grid.length;intm=grid[0].length;// Initially, every cell belongs to its own groupint[]parent=newint[n*m];int[]rank=newint[n*m];for(inti=0;i<n*m;i++)parent[i]=i;// 8 possible directionsint[]dr={-1,-1,-1,0,0,1,1,1};int[]dc={-1,0,1,-1,1,-1,0,1};// Join connected land cellsfor(intr=0;r<n;r++){for(intc=0;c<m;c++){if(grid[r][c]!='L')continue;intcurrent=r*m+c;for(intk=0;k<8;k++){intnr=r+dr[k];intnc=c+dc[k];if(nr>=0&&nr<n&&nc>=0&&nc<m&&grid[nr][nc]=='L'){intnext=nr*m+nc;unite(current,next,parent,rank);}}}}// Count unique island groupsHashSet<Integer>islands=newHashSet<>();for(intr=0;r<n;r++){for(intc=0;c<m;c++){if(grid[r][c]=='L'){intcell=r*m+c;islands.add(find(cell,parent));}}}returnislands.size();}publicstaticvoidmain(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));}
Python
# Find the parent of a celldeffind(x,parent):ifparent[x]!=x:parent[x]=find(parent[x],parent)returnparent[x]# Join two connected cellsdefunite(x,y,parent,rank):x=find(x,parent)y=find(y,parent)ifx==y:returnifrank[x]<rank[y]:parent[x]=yelifrank[x]>rank[y]:parent[y]=xelse:parent[y]=xrank[x]+=1defcountIslands(grid):n=len(grid)m=len(grid[0])# Initially, every cell belongs to its own groupparent=list(range(n*m))rank=[0]*(n*m)# 8 possible directionsdr=[-1,-1,-1,0,0,1,1,1]dc=[-1,0,1,-1,1,-1,0,1]# Join connected land cellsforrinrange(n):forcinrange(m):ifgrid[r][c]!='L':continuecurrent=r*m+cforkinrange(8):nr=r+dr[k]nc=c+dc[k]if(nr>=0andnr<nandnc>=0andnc<mandgrid[nr][nc]=='L'):next=nr*m+ncunite(current,next,parent,rank)# Count unique island groupsislands=set()forrinrange(n):forcinrange(m):ifgrid[r][c]=='L':cell=r*m+cislands.add(find(cell,parent))returnlen(islands)if__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))
C#
usingSystem;usingSystem.Collections.Generic;classGFG{// Find the parent of a cellpublicstaticintfind(intx,int[]parent){if(parent[x]!=x)parent[x]=find(parent[x],parent);returnparent[x];}// Join two connected cellspublicstaticvoidunite(intx,inty,int[]parent,int[]rank){x=find(x,parent);y=find(y,parent);if(x==y)return;if(rank[x]<rank[y])parent[x]=y;elseif(rank[x]>rank[y])parent[y]=x;else{parent[y]=x;rank[x]++;}}publicstaticintcountIslands(char[][]grid){intn=grid.Length;intm=grid[0].Length;// Initially, every cell belongs to its own groupint[]parent=newint[n*m];int[]rank=newint[n*m];for(inti=0;i<n*m;i++)parent[i]=i;// 8 possible directionsint[]dr={-1,-1,-1,0,0,1,1,1};int[]dc={-1,0,1,-1,1,-1,0,1};// Join connected land cellsfor(intr=0;r<n;r++){for(intc=0;c<m;c++){if(grid[r][c]!='L')continue;intcurrent=r*m+c;for(intk=0;k<8;k++){intnr=r+dr[k];intnc=c+dc[k];if(nr>=0&&nr<n&&nc>=0&&nc<m&&grid[nr][nc]=='L'){intnext=nr*m+nc;unite(current,next,parent,rank);}}}}// Count unique island groupsHashSet<int>islands=newHashSet<int>();for(intr=0;r<n;r++){for(intc=0;c<m;c++){if(grid[r][c]=='L'){intcell=r*m+c;islands.Add(find(cell,parent));}}}returnislands.Count;}publicstaticvoidMain(){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));}}
JavaScript
// Find the parent of a cellfunctionfind(x,parent){if(parent[x]!==x)parent[x]=find(parent[x],parent);returnparent[x];}// Join two connected cellsfunctionunite(x,y,parent,rank){x=find(x,parent);y=find(y,parent);if(x===y)return;if(rank[x]<rank[y])parent[x]=y;elseif(rank[x]>rank[y])parent[y]=x;else{parent[y]=x;rank[x]++;}}functioncountIslands(grid){letn=grid.length;letm=grid[0].length;// Initially, every cell belongs to its own groupletparent=newArray(n*m);letrank=newArray(n*m).fill(0);for(leti=0;i<n*m;i++)parent[i]=i;// 8 possible directionsletdr=[-1,-1,-1,0,0,1,1,1];letdc=[-1,0,1,-1,1,-1,0,1];// Join connected land cellsfor(letr=0;r<n;r++){for(letc=0;c<m;c++){if(grid[r][c]!=='L')continue;letcurrent=r*m+c;for(letk=0;k<8;k++){letnr=r+dr[k];letnc=c+dc[k];if(nr>=0&&nr<n&&nc>=0&&nc<m&&grid[nr][nc]==='L'){letnext=nr*m+nc;unite(current,next,parent,rank);}}}}// Count unique island groupsletislands=newSet();for(letr=0;r<n;r++){for(letc=0;c<m;c++){if(grid[r][c]==='L'){letcell=r*m+c;islands.add(find(cell,parent));}}}returnislands.size;}letgrid=[['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));