-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0463-island-perimeter.js
More file actions
43 lines (38 loc) · 1.11 KB
/
0463-island-perimeter.js
File metadata and controls
43 lines (38 loc) · 1.11 KB
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
/**
* Island Perimeter
* Time Complexity: O(R * C)
* Space Complexity: O(1)
*/
var islandPerimeter = function (grid) {
let perimeterSum = 0;
const gridRows = grid.length;
const gridColumns = grid[0].length;
const rowOffsets = [-1, 1, 0, 0];
const columnOffsets = [0, 0, -1, 1];
for (let currentRow = 0; currentRow < gridRows; currentRow++) {
for (let currentColumn = 0; currentColumn < gridColumns; currentColumn++) {
if (grid[currentRow][currentColumn] === 1) {
perimeterSum += 4;
for (
let directionIterator = 0;
directionIterator < 4;
directionIterator++
) {
const adjacentRow = currentRow + rowOffsets[directionIterator];
const adjacentColumn =
currentColumn + columnOffsets[directionIterator];
if (
adjacentRow >= 0 &&
adjacentRow < gridRows &&
adjacentColumn >= 0 &&
adjacentColumn < gridColumns &&
grid[adjacentRow][adjacentColumn] === 1
) {
perimeterSum--;
}
}
}
}
}
return perimeterSum;
};