Lesson

Given a 2D grid map of ones and zeros, with ones representing land and zeros representing water, write a function to 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 surrounded by water.

Write a function called`findIslands`

Example:

```
const map1 = [
[1, 1, 1, 1, 0],
[1, 1, 0, 1, 0],
[1, 1, 0, 0, 0],
[0, 0, 0, 0, 0]
];
console.log(findIslands(map1)); // output: 1
const map2 = [
[1, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 1]
];
console.log(findIslands(map2)); // output: 3
```

Solution Code:

```
function findIslands(grid) {
const visited = [];
for (let i = 0; i < grid.length; i++) {
visited[i] = [];
for (let j = 0; j < grid[i].length; j++) {
visited[i][j] = false;
}
}
let count = 0;
function markIsland(row, col, visited) {
if (row < 0 || col < 0 || row >= grid.length || col >= grid[0].length) {
return;
}
if (visited[row][col]) {
return;
}
visited[row][col] = true;
if (grid[row][col] === 0) {
return;
}
markIsland(row - 1, col, visited);
markIsland(row + 1, col, visited);
markIsland(row, col - 1, visited);
markIsland(row, col + 1, visited);
}
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[i].length; j++) {
if (!visited[i][j] && grid[i][j] === 1) {
markIsland(i, j, visited);
count++;
}
visited[i][j] = true;
}
}
return count;
}
```

`visited`

`grid`

`visited`

`markIsland`

`grid`

`row`

`col`

`visited`

`row`

`col`

`markIsland`

`grid`

`markIsland`

`count`

`visited`

Finally, we return the count of islands.

**Big O Complexity Analysis:**

`grid`

`grid`

`visited`

`grid`

`grid`

`grid`