Number of Islands
Last updated
Last updated
class Solution {
public int numIslands(char[][] grid) {
// V --> Vertices (nodes)
// E --> Edges (connections)
// Time complexity: O(V+E) --> Standard DFS time complexity
// Space complexity: O(V)
// Edge case
if(grid==null)
return 0;
int result = 0;
// The input is given as adjacency matrix itself.
// Hence, no pre processing is required
// Traverse through each node in the grid
for(int i=0;i<grid.length;i++) {
for(int j=0;j<grid[0].length;j++) {
if(grid[i][j]=='1') { // When land is encountered
dfs(i, j, grid); // Explore if there exists island
result++; // Increment the islandss count
}
}
}
return result;
}
private void dfs(int i, int j, char[][] grid) {
// Boundary cases
if(i<0 || i>=grid.length || j<0 || j>=grid[0].length || grid[i][j]=='0')
return;
grid[i][j] = '0'; // Marking the node as visited
dfs(i-1, j, grid); // Check up
dfs(i+1, j, grid); // Check down
dfs(i, j-1, grid); // Check left
dfs(i, j+1, grid); // Check right
}
}