695. Max Area of Island
Tags:
Medium
Skills:
Matrix
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Approach
Solution
1function maxAreaOfIsland(grid: number[][]): number {
2 const rows = grid.length;
3 const cols = grid[0].length;
4 let max_area: number = 0;
5 const directions = [
6 [1, 0], [-1, 0], [0, 1], [0, -1]
7 ]
8
9 function bfs(row: number, col: number): number {
10 const queue: [number, number][] = [[row, col]];
11 let area = 0;
12
13 while (queue.length > 0) {
14 const [r, c] = queue.shift()!;
15 grid[r][c] = 0
16 area++;
17
18 for (const [dr, dc] of directions) {
19 const new_row = dr + r;
20 const new_col = dc + c;
21
22 if (new_row >= 0 && new_row < rows && new_col >= 0 && new_col < cols && grid[new_row][new_col] === 1) {
23 queue.push([new_row, new_col]);
24 grid[new_row][new_col] = 0;
25 }
26 }
27 }
28
29 return area;
30 }
31
32 for (let i = 0; i < rows; i++) {
33 for (let j = 0; j < cols; j++) {
34 if (grid[i][j] === 1) {
35 max_area = Math.max(max_area, bfs(i, j))
36 }
37 }
38 }
39
40 return max_area;
41};