### Max Area of Island LeetCode Solution - The Coding Shala

Home >> LeetCode >> Max Area of Island

In this post, we will learn how to solve LeetCode's Max Area of Island Problem and will implement its solution in Java.

## Max Area of Island Problem

You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

The area of an island is the number of cells with a value of 1 in the island. Return the maximum area of an island in the grid. If there is no island, return 0.

**Example 1:**

Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]

Output: 6

Explanation: The answer is not 11, because the island must be connected 4-directionally.

Practice this problem on LeetCode.

## LeetCode - Max Area of Island Java Solution

**Approach 1**

Simple Solution using DFS, Recursive Approach.

**Java Program: **

class Solution { public int dfs(int[][] grid, int i, int j) { // break condition if(i < 0 || i >= grid.length || j < 0 || j >= grid[i].length || grid[i][j] == 0) { return 0; } else { // make it 0 or visited grid[i][j] = 0; return (1 + dfs(grid, i-1, j) + dfs(grid, i+1, j) + dfs(grid, i, j-1) + dfs(grid, i, j+1)); } } public int maxAreaOfIsland(int[][] grid) { int res = 0; for (int i = 0; i < grid.length; i++) { int count = 0; for (int j = 0; j < grid[i].length; j++) { if(grid[i][j] == 1) { count = dfs(grid, i, j); if(count > res) res = count; } } } return res; } }

**Other Posts You May Like**- Find Number of Islands
- Check Perfect Square
- Implement sqrt function using binary search
- LeetCode - Search in Rotated Array
- Remove duplicates from Sorted Array

## Comments

## Post a Comment