Skip to content

Commit 7fd5db8

Browse files
committed
Add solution #695
1 parent 833bfea commit 7fd5db8

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@
125125
648|[Replace Words](./0648-replace-words.js)|Medium|
126126
653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy|
127127
686|[Repeated String Match](./0686-repeated-string-match.js)|Easy|
128+
695|[Max Area of Island](./0695-max-area-of-island.js)|Medium|
128129
700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy|
129130
701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium|
130131
704|[Binary Search](./0704-binary-search.js)|Easy|

solutions/0695-max-area-of-island.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 695. Max Area of Island
3+
* https://leetcode.com/problems/max-area-of-island/
4+
* Difficulty: Medium
5+
*
6+
* You are given an m x n binary matrix grid. An island is a group of 1's (representing land)
7+
* connected 4-directionally (horizontal or vertical.) You may assume all four edges of the
8+
* grid are surrounded by water.
9+
*
10+
* The area of an island is the number of cells with a value 1 in the island.
11+
*
12+
* Return the maximum area of an island in grid. If there is no island, return 0.
13+
*/
14+
15+
/**
16+
* @param {number[][]} grid
17+
* @return {number}
18+
*/
19+
var maxAreaOfIsland = function(grid) {
20+
const cache = new Set();
21+
let max = 0;
22+
23+
for (let i = 0; i < grid.length; i++) {
24+
for (let j = 0; j < grid[0].length; j++) {
25+
max = Math.max(max, traverse(grid, cache, i, j));
26+
}
27+
}
28+
29+
return max;
30+
};
31+
32+
function traverse(grid, cache, x, y) {
33+
let count = 0;
34+
if (grid[x] && grid[x][y] === 1 && !cache.has(`${x},${y}`)) {
35+
cache.add(`${x},${y}`);
36+
count += [[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1]]
37+
.map(([x, y]) => traverse(grid, cache, x, y))
38+
.reduce((sum, count) => sum + count, 0) + 1;
39+
}
40+
return count;
41+
}

0 commit comments

Comments
 (0)