Number of Islands
Description
Given a 2d grid map of '1'
s (land) and '0'
s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: 11110 11010 11000 00000Output: 1
Example 2:
Input: 11000 11000 00100 00011Output: 3
Solution(javascript)
function DFSMarking(grid, i, j, m, n) {
if (i < 0 || j < 0 || i >= n || j >= m || grid[i][j] !== '1') return;
grid[i][j] = '0';
DFSMarking(grid, i + 1, j, m, n);
DFSMarking(grid, i - 1, j, m, n);
DFSMarking(grid, i, j + 1, m, n);
DFSMarking(grid, i, j - 1, m, n);
}
/**
* @param {character[][]} grid
* @return {number}
*/
var numIslands = function(grid) {
let count = 0;
const n = grid.length;
if (n === 0) return 0;
const m = grid[0].length;
for (let i = 0; i < n; i++){
for (let j = 0; j < m; j++)
if (grid[i][j] === '1') {
DFSMarking(grid, i, j, m, n);
++count;
}
}
return count;
};