Hello Coders, Today, I give another solution for the Leetcode problem which is the ” Number of Islands Leetcode Solution “.
But before moving on to the solution, let’s take a look at the problem statement.
Problem Statement:
Given an m x n
2D binary grid grid
which represents a map of '1'
s (land) and '0'
s (water), return 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 1:
Input: grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] Output: 1
Example 2:
Input: grid = [ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ] Output: 3
Number of Islands Leetcode Solution in Java
//Number of Islands Leetcode Solution 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); result++; } } } 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'){ return; } grid[i][j] = '0'; numIslandsDfs(grid, i+1, j); numIslandsDfs(grid, i-1, j); numIslandsDfs(grid, i, j+1); numIslandsDfs(grid, i, j-1); } } //Number of Islands Leetcode Solution in Java
Disclaimer: This problem(Number of Islands Leetcode solution) is originally created by Leetcode. Codesagar only provides a solution for it. This solution is only for Educational and learning purposes.