Skip to content

Commit a030b30

Browse files
committed
Island Perimeter
1 parent eb86c13 commit a030b30

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Source : https://leetcode.com/problems/island-perimeter/
2+
// Author : Han Zichi
3+
// Date : 2016-11-20
4+
5+
/**
6+
* @param {number[][]} grid
7+
* @return {number}
8+
*/
9+
var islandPerimeter = function(grid) {
10+
if (grid.length === 0)
11+
return 0;
12+
13+
let n = grid.length
14+
, m = grid[0].length
15+
, ans = 0;
16+
17+
const dir = [[1, 0], [-1, 0], [0, 1], [0, -1]];
18+
19+
for (let i = 0; i < n; i++)
20+
for (let j = 0; j < m; j++) {
21+
if (!grid[i][j])
22+
continue;
23+
24+
for (let l = 0; l < 4; l++) {
25+
let neighbourCellX = i + dir[l][0];
26+
let neighbourCellY = j + dir[l][1];
27+
28+
if (neighbourCellX < 0 || neighbourCellX >= n
29+
|| neighbourCellY < 0 || neighbourCellY >= m) {
30+
ans += 1;
31+
continue;
32+
}
33+
34+
ans += !grid[neighbourCellX][neighbourCellY];
35+
}
36+
}
37+
38+
return ans;
39+
};

0 commit comments

Comments
 (0)