let numIslands = function(matrix) {
if (!matrix.length) return 0;
let land = 1, visited = 'X',
counter = 0,
maxRow = matrix.length - 1,
maxCol = matrix[0].length - 1;
function exploreAndMark(row, col) {
if (row < 0 || col < 0 || row > maxRow || col > maxCol) {
return;
}
if (matrix[row][col] === land) {
matrix[row][col] = visited;
// explore up
exploreAndMark(row - 1, col);
// explore down
exploreAndMark(row + 1, col);
// explore left
exploreAndMark(row, col - 1);
// explore right
exploreAndMark(row, col + 1);
}
}
for (let row = 0; row <= maxRow; row++) {
for (let col = 0; col <= maxCol; col++) {
if (matrix[row][col] === land) {
counter++;
exploreAndMark(row, col);
}
}
}
return counter;
}