Leetcode 695. Max Area of Island
Given a non-empty 2D array grid
of 0’s and 1’s, 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.
Find the maximum area of an island in the given 2D array. If there is no island, return 0.
public class Solution {
public int maxAreaOfIsland(int[][] grid) {
int maxArea = 0;
// Dimensions of the grid
int rows = grid.length;
int cols = grid[0].length;
// Iterate through every cell in the grid
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == 1) {
// Calculate the area of the island using DFS or BFS
int area = dfs(grid, r, c);
// Update the maximum area found so far
maxArea = Math.max(maxArea, area);
}
}
}
return maxArea;
}
private int dfs(int[][] grid, int r, int c) {
// Boundary and base condition checks
if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] == 0) {
return 0;
}
// Mark the cell as visited by setting it to 0
grid[r][c] = 0;
int area = 1; // Counting the current cell
// Explore all four possible directions
area += dfs(grid, r + 1, c); // down
area += dfs(grid, r - 1, c); // up
area += dfs(grid, r, c + 1); // right
area += dfs(grid, r, c - 1); // left
return area;
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?