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