-
Notifications
You must be signed in to change notification settings - Fork 0
/
695_Max Area of Island.js
56 lines (51 loc) · 1.23 KB
/
695_Max Area of Island.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// https://leetcode.com/problems/max-area-of-island/description/
/**
* @param {number[][]} grid
* @return {number}
*/
var maxAreaOfIsland = function (grid) {
let result = 0;
let height = grid.length;
let width = grid[0].length;
let getArea = (i, j) => {
if (grid[i][j] === 0) {
return 0;
} else {
grid[i][j] = 0;
}
let area = 1;
if (i <= height - 2) {
area += getArea(i + 1, j);
}
if (i >= 1) {
area += getArea(i - 1, j);
}
if (j <= width - 2) {
area += getArea(i, j + 1);
}
if (j >= 1) {
area += getArea(i, j - 1);
}
return area;
}
for (let i = 0; i < height; i++) {
for (let j = 0; j < width; j++) {
if (grid[i][j] === 1) {
let tempArea = getArea(i, j);
result = Math.max(result, tempArea);
}
}
}
return result;
};
var grid = [
[0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0],
[0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0]
];
console.log(maxAreaOfIsland(grid));