LeetCode 695: Max Area of Island Solution
Master LeetCode problem 695 (Max Area of Island), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
695. Max Area of Island
Problem Explanation
Explanation:
To solve this problem, we can use Depth First Search (DFS) to explore each cell in the grid. We will start DFS from each cell with a value of 1 and calculate the area of the island connected to that cell. We will keep track of the maximum area found so far and return it as the result.
- Initialize a variable
maxAreato store the maximum area found. - Iterate over each cell in the grid:
- If the cell value is 1, start DFS from that cell to explore the connected island.
- During DFS, mark the visited cell as 0 to avoid revisiting it.
- Calculate the area of the island during DFS and update
maxAreaif a larger area is found.
- Return the
maxAreaas the result.
Time Complexity: O(mn) where m is the number of rows and n is the number of columns in the grid. Space Complexity: O(mn) for the recursive stack and visited array.
:
Solution Code
class Solution {
public int maxAreaOfIsland(int[][] grid) {
int maxArea = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
maxArea = Math.max(maxArea, dfs(grid, i, j));
}
}
}
return maxArea;
}
private int dfs(int[][] grid, int i, int j) {
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0) {
return 0;
}
grid[i][j] = 0;
int area = 1;
area += dfs(grid, i + 1, j);
area += dfs(grid, i - 1, j);
area += dfs(grid, i, j + 1);
area += dfs(grid, i, j - 1);
return area;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 695 (Max Area of Island)?
This page provides optimized solutions for LeetCode problem 695 (Max Area of Island) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 695 (Max Area of Island)?
The time complexity for LeetCode 695 (Max Area of Island) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 695 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 695 in Java, C++, or Python.