-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathisland-perimeter.js
More file actions
39 lines (31 loc) · 837 Bytes
/
island-perimeter.js
File metadata and controls
39 lines (31 loc) · 837 Bytes
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
// Source : https://leetcode.com/problems/island-perimeter/
// Author : Han Zichi
// Date : 2016-11-20
/**
* @param {number[][]} grid
* @return {number}
*/
var islandPerimeter = function(grid) {
if (grid.length === 0)
return 0;
let n = grid.length
, m = grid[0].length
, ans = 0;
const dir = [[1, 0], [-1, 0], [0, 1], [0, -1]];
for (let i = 0; i < n; i++)
for (let j = 0; j < m; j++) {
if (!grid[i][j])
continue;
for (let l = 0; l < 4; l++) {
let neighbourCellX = i + dir[l][0];
let neighbourCellY = j + dir[l][1];
if (neighbourCellX < 0 || neighbourCellX >= n
|| neighbourCellY < 0 || neighbourCellY >= m) {
ans += 1;
continue;
}
ans += !grid[neighbourCellX][neighbourCellY];
}
}
return ans;
};