Leetcode 695. 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
.
m
and n
(the dimensions of the grid)?
m
and n
could range from 1 to 50 or 1 to 100.0
s and 1
s, correct?
1
values in the grid?
0
.We’ll use Depth-First Search (DFS) to explore each island and compute its area. Once an island is fully traversed, we will update our maximum area if the current island’s area is larger than the previously recorded maximum.
Steps:
1
is encountered, perform DFS to find the full extent of the island.0
to avoid revisiting.1
s encountered during the DFS (which gives the area of the island).#include <vector>
#include <algorithm>
class Solution {
public:
int maxAreaOfIsland(std::vector<std::vector<int>>& grid) {
if (grid.empty() || grid[0].empty()) return 0;
int max_area = 0;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[0].size(); j++) {
if (grid[i][j] == 1) {
int area = dfs(grid, i, j);
max_area = std::max(max_area, area);
}
}
}
return max_area;
}
private:
int dfs(std::vector<std::vector<int>>& grid, int i, int j) {
if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() || grid[i][j] == 0) {
return 0;
}
grid[i][j] = 0; // Mark the cell as visited by changing it to 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;
}
};
1
s.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?