Skip to content

Instantly share code, notes, and snippets.

@misaxi
Created June 29, 2018 05:08
Show Gist options
  • Save misaxi/c93c6c5888da14ef7c375aaca201ee9a to your computer and use it in GitHub Desktop.
Save misaxi/c93c6c5888da14ef7c375aaca201ee9a to your computer and use it in GitHub Desktop.
function getPerimeter(matrix) {
let sum = 0;
for(let i = 0; i < matrix.length; i++) {
let row = matrix[i]
for(let j = 0; j < row.length; j++) {
if (isLand(matrix, i, j)) {
sum += 4;
if (isLand(matrix, i - 1, j)) {
sum--;
}
if (isLand(matrix, i + 1, j)) {
sum--;
}
if (isLand(matrix, i, j - 1)) {
sum--;
}
if (isLand(matrix, i, j + 1)) {
sum--;
}
}
}
}
return sum;
}
function isLand(matrix, i, j) {
if (i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length) {
return false;
}
return matrix[i][j] == 1;
}
getPerimeter([
[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment