JSFiddle - React, Tailwind, and code Playground
by Udi Talias
JavaScript
class Island {
constructor(grid) {
this.grid = grid;
}
getCount() {
let count = 0;
let i, j;
const self = this;
// side effect - use with causion!
function isIsland(outer, inner) {
outer = !isNaN(outer) ? outer : i;
inner = !isNaN(inner) ? inner : j;
if(outer < 0 || inner < 0) return false;
return !!self.grid[outer][inner];
}
for(i = 0; i < this.grid.length; i++) {
for(j = 0; j < this.grid[i].length; j++) {
if(isIsland() && !isIsland(i - 1, j - 1) && !isIsland(i - 1, j) && !isIsland(i - 1, j + 1) && !isIsland(i, j - 1)) {
count++;
}
}
}
return count;
}
}
alert(new Island(
[
[1, 1, 1, 0, 0],
[0, 0, 0, 1, 1],
[1, 1, 0, 0, 1]
]
).getCount());
/* alert(new Island(
[
[1, 1, 0, 0, 0],
[0, 1, 0, 0, 1],
[1, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[1, 0, 1, 0, 1]
]
).getCount()); */