Tuesday, June 1, 2021

leetcode Max Area of Island Solution (Max Area of Island) (leetcode june 2021 challenge)

Max Area of Island



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 1 in the island.

Return the maximum area of an island in grid. If there is no island, return 0.

 

Example 1:





 

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.

 

Example 2:

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

Output: 3

Constraints:

·         m == grid.length

·         n == grid[i].length

·         1 <= m, n <= 50

·         grid[i][j] is either 0 or 1.

 

Solution 1:

public class maxAreaOfIsland {

    public static int length(int[][] gridint iint j) {

        if (i >= grid.length || j >= grid[0].length || i < 0 || j < 0 || grid[i][j] != 1)
            return 0;
        int ans = 0;
        grid[i][j] = 2;
        if (j + 1 < grid[0].length && grid[i][j + 1] == 1)
            ans = ans + 1 + length(gridij + 1);
        if (i + 1 < grid.length && grid[i + 1][j] == 1)
            ans = ans + 1 + length(gridi + 1j);
        if (j - 1 >= 0 && grid[i][j - 1] == 1)
            ans = ans + 1 + length(gridij - 1);
        if (i - 1 >= 0 && grid[i - 1][j] == 1)
            ans = ans + 1 + length(gridi - 1j);
        return ans;
    }

    public static int Solution(int[][] grid) {
        int ans = 0;
        for (int i = 0i < grid.lengthi++) {
            for (int j = 0j < grid[0].lengthj++) {
                if (grid[i][j] == 1)
                    ans = Math.max(anslength(gridij) + 1);
            }
        }

        return ans;
    }


Climate Crisis and Innovation: Navigating Earth's Future

Climate Change: Recent Events and Technological Solutions 1. The Escalating Climate Crisis The climate crisis has intensified in recent year...