๐๏ธ Leetcode-695 : "Max Area of Island" โ Full Approach and Code Breakdown


Problem Statement
You are given a 2D grid where:
1
represents land
0
represents waterFind the area of the largest island in the grid.
(An island is made of connected 1's โ connected horizontally or vertically.)
Approach
To solve this, we use Depth-First Search (DFS).
Here's the high-level idea:
We traverse the grid cell by cell.
When we find an unvisited land cell (
1
), we start a DFS to explore the full island connected to that cell.During the DFS:
We mark every visited land cell to avoid re-visiting.
We count how many cells are part of the current island.
We keep track of the maximum area found across all islands.
Visualizing the flow:
1. Start at an unvisited land cell (1)
2. DFS: Move in 4 directions (up, down, left, right)
3. Count all connected land cells
4. Update maxArea if needed
5. Continue scanning the grid
Step-by-Step Code Explanation
Here's the full code first:
var maxAreaOfIsland = function(grid) {
let rows = grid.length;
let cols = grid[0].length;
let areaIsland = 0;
let visited = Array(rows).fill(0).map(() => Array(cols).fill(0));
function dfs(row, col, visited, grid) {
let directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];
visited[row][col] = 1;
let area = 1;
for (let [dr, dc] of directions) {
let nr = dr + row;
let nc = dc + col;
if (nr >= 0 && nc >= 0 && nr < rows && nc < cols && grid[nr][nc] === 1 && !visited[nr][nc]) {
area += dfs(nr, nc, visited, grid);
}
}
return area;
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (!visited[i][j] && grid[i][j] === 1) {
let newArea = dfs(i, j, visited, grid);
areaIsland = Math.max(areaIsland, newArea);
}
}
}
return areaIsland;
};
Now let's go through it bit-by-bit:
1. Initialize variables
let rows = grid.length;
let cols = grid[0].length;
let areaIsland = 0;
let visited = Array(rows).fill(0).map(() => Array(cols).fill(0));
rows
,cols
: Store the dimensions of the grid.areaIsland
: Keep track of the maximum area found so far.visited
: Create a 2D array to mark visited cells. Initially, all cells are unvisited (0
).
2. Define the DFS function
function dfs(row, col, visited, grid) {
let directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];
visited[row][col] = 1;
let area = 1;
dfs(row, col)
: Starts exploring from a given cell.directions
: Define 4 possible moves (down, up, right, left).visited[row][col] = 1
: Mark current cell as visited.area = 1
: Current cell itself counts as area1
.
3. Explore all 4 directions
for (let [dr, dc] of directions) {
let nr = dr + row;
let nc = dc + col;
if (nr >= 0 && nc >= 0 && nr < rows && nc < cols && grid[nr][nc] === 1 && !visited[nr][nc]) {
area += dfs(nr, nc, visited, grid);
}
}
For each direction:
Calculate the new row
nr
and new columnnc
.Check boundaries to stay inside the grid.
Check if the new cell is land (
1
) and not visited.If so, recursively call
dfs
and add the returned area to currentarea
.
4. Return the total area from DFS
return area;
- After exploring all directions, return the total island area found starting from this cell.
5. Traverse the grid
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (!visited[i][j] && grid[i][j] === 1) {
let newArea = dfs(i, j, visited, grid);
areaIsland = Math.max(areaIsland, newArea);
}
}
}
Scan every cell in the grid.
If we find an unvisited land cell (
1
), start a DFS.Get the area returned by DFS and update
areaIsland
if it's larger than the previous maximum.
6. Final Result
return areaIsland;
- After checking all cells, return the maximum island area found.
Time and Space Complexity Analysis
Time Complexity:
O(rows ร cols)
Each cell is visited at most once.
Space Complexity:
O(rows ร cols)
Due to the
visited
matrix and recursive call stack in the worst case.
Conclusion
โ
We successfully used DFS to solve the "Max Area of Island" problem.
โ
We carefully handled boundary checks, visited marking, and area calculation.
โ
Understanding how recursion aggregates the area is the key trick!
โจ Final Notes
Always be careful with types:
"1"
(string) vs1
(number)!Always declare new variables with
let
orconst
to avoid bugs.DFS is a powerful tool whenever you need to explore connected components.
๐ Stay tuned for more DFS, BFS, and graph problems! ๐
Subscribe to my newsletter
Read articles from Deepak Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
