Number of Islands GFG Solution in Java

Hello coders, This is another problem from GFG practice named “Number of Islands “.

Problem Statement:

Given a grid of size n*m (n is the number of rows and m is the number of columns in the grid) 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.

Input: grid = {{0,1},{1,0},{1,1},{1,0}}

Output: 1


The grid is-

0 1

1 0

1 1

1 0

All lands are connected.

Number of Islands GFG Soution in Java

class Solution {
    public int numIslands(char[][] grid) {
        int result = 0;
        for(int i=0; i<grid.length; i++){
            for(int j =0; j<grid[i].length; j++){
                if(grid[i][j] == '1'){
                    numIslandsDfs(grid, i, j);
        return result;

    private void numIslandsDfs(char[][] grid, int i, int j) {
        if(i<0 || i>=grid.length || j<0 || j>=grid[i].length || grid[i][j] != '1'){
        grid[i][j] = '0';
        numIslandsDfs(grid, i+1, j);
        numIslandsDfs(grid, i-1, j);
        numIslandsDfs(grid, i, j+1);
        numIslandsDfs(grid, i, j-1);
        numIslandsDfs(grid, i+1, j+1);
        numIslandsDfs(grid, i-1, j+1);
        numIslandsDfs(grid, i+1, j-1);
        numIslandsDfs(grid, i-1, j-1);

Disclaimer: This problem(Minimum Number of Jumps) is originally created by GeeksforGeeksCodesagar only provides a solution for it. This solution is only for Educational and learning purposes.

Leave a Comment