InterviewPrep

Leetcode 200 Number of Islands (Java) With Video Explanation

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example :

Input:
11000
11000
00100
00011

Output: 3

Solution:
We will solve this problem using DFS(Depth First Search) Algorithm tracing all the 1’s until we find no 1’s on 4 sides recursively then we will increase the count.

class Solution {
    public int numIslands(char[][] grid) {
        if(grid.length==0) return 0;
        int rows = grid.length;
        int columns = grid[0].length;
        int noOfIslands = 0;
        for(int i=0;i<rows;i++){
            for(int j=0;j<columns;j++){
                if(grid[i][j]=='1'){
                    dfs(grid, i, j);
                    noOfIslands++;
                }
            }
        }
        
        return noOfIslands;
    }
    
    private void dfs(char[][] grid, int i, int j){
        if(i<0 || j<0 ||i>=grid.length|| j>=grid[0].length|| grid[i][j]!='1') return;
        grid[i][j] = '2';
        dfs(grid, i+1, j);
        dfs(grid, i, j+1);
        dfs(grid, i-1, j);
        dfs(grid, i, j-1);
        
    }
}
rajendra

Recent Posts

Largest Unique Number Java Solution

Question : Given an array of integers A, return the largest integer that only occurs once.…

10 months ago

Jump Search Algorithm In Java

Jump search algorithm is a pretty new algorithm to search for an element in a…

1 year ago

Knuth Morris Pratt Pattern Search Algorithm

What is Knuth Morris Pratt or KMP algorithm ? KMP is an algorithm which is…

1 year ago

Binary Search Algorithm In Java

Binary Search is a Logarithmic search which finds the target element in a sorted array…

2 years ago

Leetcode Integer to Roman Java Solution

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X…

2 years ago

Leetcode Container With Most Water Java Solution

Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such…

2 years ago

This website uses cookies.