Created
June 29, 2018 05:08
-
-
Save misaxi/c93c6c5888da14ef7c375aaca201ee9a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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