JSFiddle - React, Tailwind, and code Playground
JavaScript
const IslandTokens = Object.freeze({
ISLAND: "1",
SEA: "0",
SUNK: "."
});
function getIslandAndSink(arr, x, y) {
if (y < 0 || y >= arr.length || x < 0 || x >= arr[0].length) return 0;
if (arr[y][x] !== IslandTokens.ISLAND) {
return 0;
} else {
arr[y][x] = IslandTokens.SUNK;
[-1, 1].forEach( delta => getIslandAndSink(arr, x + delta, y) );
[-1, 1].forEach( delta => getIslandAndSink(arr, x, y + delta) );
return 1;
}
}
var numIslands = function(grid) {
var x, y, count = 0;
grid = grid.map( s => s.split("") )
for (y = 0; y < grid.length; y++) {
for (x = 0; x < grid[y].length; x++) {
count += getIslandAndSink(grid, x, y)
}
}
return count;
};
console.assert(numIslands(["11110","11010","11000","00000"]) === 1)
console.assert(numIslands(["11110","11010","11000","00001"]) === 2)
console.assert(numIslands(["11110","11010","11000","00101"]) === 3)
console.assert(numIslands([
"0 1 0 1 0",
"0 0 1 1 1",
"1 0 0 1 0",
"0 1 1 0 0",
"1 0 1 0 1"].map( s => s.split(" ").join("") )) === 6);
console.assert(numIslands([
"0 1 0 1 0",
"0 0 1 1 1",
"1 0 0 1 0",
"0 1 1 0 1"].map( s => s.split(" ").join("") )) === 5);