Find the number of islands | Practice | GeeksforGeeks

Given a grid of size n*m (n is number of rows and m is number of columns grid has) consisting of '0's(Water) and '1's(Land). Find the number of islands.
Note: An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically or diagonally i.e., in all 8 directions.
 
Example 1:
Input:
grid = {{0,1},{1,0},{1,1},{1,0}}
Output:
1
Explanation:
The grid is-
0 1
1 0
1 1
1 0
All lands are connected.

Example 2:
Input:
grid = {{0,1,1,1,0,0,0},{0,0,1,1,0,1,0}}
Output:
2
Expanation:
The grid is-
0 1 1 1 0 0 0
0 0 1 1 0 1 0 
There are two islands one is colored in blue 
and other in orange.

 
Your Task:
You don't need to read or print anything. Your task is to complete the function numIslands() which takes grid as input parameter and returns the total number of islands.
 
Expected Time Compelxity: O(n*m)
Expected Space Compelxity: O(n*m)
 
Constraints:
1 ≤ n, m ≤ 500
0
thakuraditya6211 day ago
Java Easy To Understand :)
// Function to find the number of islands.
    public int numIslands(char[][] grid) {
        // Code here
        boolean [][]visited = new boolean[grid.length][grid[0].length];
        int count = 0;
        for(int i = 0; i < grid.length; i++){
            for(int j = 0; j < grid[i].length; j++){
                if(grid[i][j] == '1' && visited[i][j] == false){
                dfs(grid, i, j , visited);
                count++;
                }
            }
        }
        return count;
    }
    
    public void dfs(char[][] grid, int i, int j, boolean[][] visited){
        // base case like out of 
        if(i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] == '0' || visited[i][j] == true){
            return  ;
        }
        visited[i][j] = true;
        
        // vertically and horizontally
        dfs(grid, i-1, j, visited);
        dfs(grid, i, j+1, visited);
        dfs(grid, i, j-1, visited);
        dfs(grid, i+1, j, visited);
        
        // diagonally
        dfs(grid, i+1, j+1, visited);
        dfs(grid, i-1, j-1, visited);
        dfs(grid, i-1, j+1, visited);
        dfs(grid, i+1, j-1, visited);

    }
+1
kharsh8221 day ago
Java Easy Solution
// { Driver Code Starts
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
    public static void main(String[] args) throws IOException {
        BufferedReader br =
            new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine().trim());
        while (T-- > 0) {
            String[] s = br.readLine().trim().split(" ");
            int n = Integer.parseInt(s[0]);
            int m = Integer.parseInt(s[1]);
            char[][] grid = new char[n][m];
            for (int i = 0; i < n; i++) {
                String[] S = br.readLine().trim().split(" ");
                for (int j = 0; j < m; j++) {
                    grid[i][j] = S[j].charAt(0);
                }
            }
            Solution obj = new Solution();
            int ans = obj.numIslands(grid);
            System.out.println(ans);
        }
    }
}// } Driver Code Ends


class Solution {
    // Function to find the number of islands.
    
    public int numIslands(char[][] grid) {
        // Code here
        boolean [][] visited=new boolean[grid.length][grid[0].length];
        int count=0;
        for(int i =0;i<grid.length;i++){
            for(int j =0;j<grid[i].length;j++){
                if(grid[i][j]=='1' && visited[i][j]==false){
                    helper(grid,visited,i,j);
                    count++;
                }
            }
        }
        
        return count ;
    }
    
    public void helper(char[][] grid,boolean [][] visited,int r,int c){
        
        if(r<0 || c<0 || r>=grid.length || c>=grid[0].length || grid[r][c]=='0' || visited[r][c]==true ){
            return ;
        }
        
        visited[r][c]=true;
        
        // Vertical and Horizontal Direction 
        helper(grid,visited,r+1,c);
        helper(grid,visited,r-1,c);
        helper(grid,visited,r,c+1);
        helper(grid,visited,r,c-1);
        
        // Diagonally 
        helper(grid,visited,r+1,c+1);
        helper(grid,visited,r-1,c-1);
        helper(grid,visited,r-1,c+1);
        helper(grid,visited,r+1,c-1);
        
    }
}
0
gourangp293 days ago
class Solution { public:   // Function to find the number of islands.   void dfs(int i,int j, vector<vector<int>>& visited, vector<vector<char>>& grid, int& n, int& m)   {       if(i<0 || i>=n || j<0 || j>=m || grid[i][j] == '0' || visited[i][j] == 1) return;       visited[i][j] = 1;       int dx[8] = {-1,-1,-1,0,0,1,1,1};       int dy[8] = {-1,0,1,-1,1,-1,0,1};       for(int k=0; k<8; k++)       {           dfs(i+dx[k],j+dy[k],visited,grid,n,m);       }   }   int numIslands(vector<vector<char>>& grid) {       // Code here       int n = grid.size();       int m = grid[0].size();       int ans=0;       vector<vector<int>> visited(n, vector<int> (m,0));       for(int i=0; i<n; i++)       {           for(int j=0; j<m; j++)           {               if(visited[i][j] == 0 && grid[i][j] == '1')               {                   ans++;                   dfs(i,j,visited,grid,n,m);               }           }       }       return ans;   }};
0
jordiamposta1 week ago
// C++
//---
class Solution{
public:

    int numIslands(vector<vector<char>>& grid) {
        if (grid.empty())
            return 0;

        int isle_counter = 0;

        auto visited_cells = std::vector<std::vector<bool>>(
                grid.size(), std::vector<bool>(grid[0].size(), false));

        const std::vector<std::pair<int, int>> look_positions_ {
                {1,  -1}, {1, 0}, {1, 1},
                {-1, -1}, {-1, 0}, {-1, 1},
                {0,  -1}, {0,  1},
        };

        auto _grow = [&](int row, int col, auto && _grow) -> void {
                    for (auto &position: look_positions_) {
                        if (
                                (position.first + row < 0 || position.first + row >= grid.size()) ||
                                (position.second + col < 0 || position.second + col >= grid[0].size()) ||
                                visited_cells[position.first + row][position.second + col]
                                ){
                            continue;
                        }

                        auto land = grid[position.first + row][position.second + col];
                        visited_cells[position.first + row][position.second + col] = true;

                        if (land == '1') {
                            _grow(position.first + row, position.second + col, _grow);
                        }
                    }
                };

        for(int i=0; i < grid.size(); i++)
        {
            for (int j = 0; j < grid[i].size(); j++) {
                if (grid[i][j]=='1' && (!visited_cells[i][j])) {
                    visited_cells[i][j] = true;
                    _grow(i, j, _grow);
                    isle_counter++;
                }
            }
        }

        return isle_counter;
    }
};
0
amishasahu3282 weeks ago
void mark_current_island(vector<vector<char>>& grid, int r, int c, int row, int col)
    {
        // Boundary conditions
        if(r < 0 || r >= row || c < 0 || c >= col || grid[r][c] != '1')
            return;
        
        // mark current island as visited
        grid[r][c] = '2';
        
        // mark all its neighbour visisted
        mark_current_island(grid, r-1, c, row, col); // up
        mark_current_island(grid, r+1, c, row, col); // down
        mark_current_island(grid, r, c-1, row, col); // left
        mark_current_island(grid, r, c+1, row, col); // right
        mark_current_island(grid, r-1, c-1, row, col); // left up diagonal
        mark_current_island(grid, r+1, c-1, row, col); // left down diagonal
        mark_current_island(grid, r+1, c+1, row, col); // right down diagonal
        mark_current_island(grid, r-1, c+1, row, col); // right up diagonal
        
    }
    int numIslands(vector<vector<char>>& grid) {
        // Code here
        int row = grid.size();
        int col = grid[0].size();
        
        int numberOfIsland = 0;
        for(int i = 0; i < row; i++)
        {
            for(int j = 0; j < col; j++)
            {
                if(grid[i][j] == '1')
                {
                    mark_current_island(grid, i, j , row, col);
                    numberOfIsland++;
                }
            }
        }
        return numberOfIsland;
    }
0
lilith2 weeks ago
JAVA Soln
class Solution {
    // Function to find the number of islands.
    public int numIslands(char[][] grid) {
        // Code here
        int res = 0;
        boolean[][] visited = new boolean[grid.length][grid[0].length];
        
        for(int i = 0; i < grid.length; i++)
            for(int j = 0; j < grid[0].length; j++) 
                if(grid[i][j] == '1' && visited[i][j] != true) {
                    findIsLands(grid, i , j, visited);
                    res++;
                }
                
        return res;
    }
    
    public void findIsLands(char[][] grid, int i, int j, boolean[][] visited) {
        if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0' || visited[i][j])
            return;
            
        visited[i][j] = true;
            
        findIsLands(grid, i - 1, j, visited);
        findIsLands(grid, i + 1, j, visited);
        findIsLands(grid, i, j - 1, visited);
        findIsLands(grid, i, j + 1, visited);
        findIsLands(grid, i + 1, j - 1, visited);
        findIsLands(grid, i - 1, j + 1, visited);
        findIsLands(grid, i - 1, j - 1, visited);
        findIsLands(grid, i + 1, j + 1, visited);
    }
}
0
lilith
This comment was deleted.
-1
joyrockok3 weeks ago
class Solution {   // Function to find the number of islands.int dirRow[] = {-1, -1, -1, 0, 0, 1, 1, 1}; int dirCol[] = {-1, 0, 1, -1, 1, -1, 0, 1};int n, m;public boolean isOk(char[][] grid, int i, int j, boolean visited[][]) {  if(i>=0 && i < n && j >=0 && j < m && visited[i][j] == false && (grid[i][j]-'0') == 1) {  return true; }  return false;}public void DFS(char[][] grid, int row, int col, boolean visited[][]) { visited[row][col] = true;  for(int k=0; k<8; k++) {    if(isOk(grid, row+dirRow[k], col+dirCol[k], visited)) {       DFS(grid, row+dirRow[k], col+dirCol[k], visited);    } }}   public int numIslands(char[][] grid) {       // Code here    int count=0;        n = grid.length;    m = grid[0].length;        boolean [][]visited = new boolean[n][m];        for(int i=0; i<n; i++) {     for(int j=0; j<m; j++) {      if(isOk(grid, i, j, visited) == true) {       DFS(grid, i, j, visited);       count++;      }     }    }        return count;   }}
0
patildhiren443 weeks ago
JAVA - 0.2
 
void isValid(int i, int j, boolean[][]visit, char[][]arr, int n, int m){
        if(i<0 || j<0 || i>=n || j>=m){
            return ;
        }
        
        if(arr[i][j]=='0'){
            return;
        }
        
        if(visit[i][j]==false){
            visit[i][j]=true;
            
            isValid(i+1, j, visit, arr, n, m);
            isValid(i, j+1, visit, arr, n, m);
            isValid(i-1, j, visit, arr, n, m);
            isValid(i, j-1, visit, arr, n, m);
            
            isValid(i+1, j+1, visit, arr, n, m);
            isValid(i+1, j-1, visit, arr, n, m);
            isValid(i-1, j-1, visit, arr, n, m);
            isValid(i-1, j+1, visit, arr, n, m);
        }
    }
    
    public int numIslands(char[][] grid) {
        // Code here
        int n=grid.length, m=grid[0].length;
        boolean[][]visit = new boolean[n][m];
        
        int cou=0;
        for(int i=0; i<n; i++){
            for(int j=0; j<m; j++){
                if(grid[i][j]=='1' && visit[i][j]==false){
                    isValid(i, j, visit, grid, n, m);
                    cou++;
                }
            }
        }
        return cou;
    }
 
+1
milindprajapatmst193 weeks ago
int dx[] = { 0, 1, 1,  1,  0, -1, -1, -1 };
int dy[] = { 1, 1, 0, -1, -1, -1,  0,  1 };
class Solution {
  public:
    void dfs(int x, int y, int n, int m, vector<vector<char>>& grid) {
        grid[x][y] = '0';
        for (int k = 0; k < 8; k++) {
            int a = x + dx[k], b = y + dy[k];
            if (0 <= a && a < n && 0 <= b && b < m && grid[a][b] == '1')
                dfs(a, b, n, m, grid);
        }
    }
    int numIslands(vector<vector<char>>& grid) {
        int n = grid.size(), m = grid[0].size(), result = 0;
        for (int x = 0; x < n; x++) {
            for (int y = 0; y < m; y++) {
                if (grid[x][y] == '0')
                    continue;
                result++;
                dfs(x, y, n, m, grid);
            }
        }
        return result;
    }
};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.