Saturday, March 12, 2022

Leet Code - 695: Max Area of Island

https://leetcode.com/problems/max-area-of-island/


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.

package pep.Day40;

public class Max_Area_Of_Island {

public static void main(String[] args) {
int[][] 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}
};

System.out.println(maxAreaOfIsland(grid));
}

public static int maxAreaOfIsland(int[][] grid) {

int max_size = 0;

for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
int size = dfs(grid, i, j);
max_size = Math.max(size, max_size);
}
}
}

return max_size;

}

public static int dfs(int[][] grid, int row, int col) {
int size = 1;
grid[row][col] = 0;

int[][] dirns = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
for (int[] dir : dirns) {
int x = dir[0] + row;
int y = dir[1] + col;

if ((x >= 0 && x < grid.length) && (y >= 0 && y < grid[0].length)) {
if (grid[x][y] == 1) {
size += dfs(grid, x, y);
}

}

}
return size;

}
}


No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...