**Physical Address**

304 North Cardinal St.

Dorchester Center, MA 02124

Given an `m x n`

2D binary grid `grid`

which represents a map of `'1'`

s (land) and `'0'`

s (water), return *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: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
```

**Example 2:**

```
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
```

**Constraints:**

`m == grid.length`

`n == grid[i].length`

`1 <= m, n <= 300`

`grid[i][j]`

is`'0'`

or`'1'`

.

```
def numIslands(self, grid):
def sink(i, j):
if 0 <= i < len(grid) and 0 <= j < len(grid[i]) and grid[i][j] == '1':
grid[i][j] = '0'
map(sink, (i+1, i-1, i, i), (j, j, j+1, j-1))
return 1
return 0
return sum(sink(i, j) for i in range(len(grid)) for j in range(len(grid[i])))
```

```
public class Solution {
char[][] g;
public int numIslands(char[][] grid) {
int islands = 0;
g = grid;
for (int i=0; i<g.length; i++)
for (int j=0; j<g[i].length; j++)
islands += sink(i, j);
return islands;
}
int sink(int i, int j) {
if (i < 0 || i == g.length || j < 0 || j == g[i].length || g[i][j] == '0')
return 0;
g[i][j] = '0';
sink(i+1, j); sink(i-1, j); sink(i, j+1); sink(i, j-1);
return 1;
}
}
```

```
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int m = grid.size(), n = m ? grid[0].size() : 0, islands = 0, offsets[] = {0, 1, 0, -1, 0};
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
islands++;
grid[i][j] = '0';
queue<pair<int, int>> todo;
todo.push({i, j});
while (!todo.empty()) {
pair<int, int> p = todo.front();
todo.pop();
for (int k = 0; k < 4; k++) {
int r = p.first + offsets[k], c = p.second + offsets[k + 1];
if (r >= 0 && r < m && c >= 0 && c < n && grid[r][c] == '1') {
grid[r][c] = '0';
todo.push({r, c});
}
}
}
}
}
}
return islands;
}
};
```

In our experience, we suggest you solve this Number of Islands LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Number of Islands LeetCode Solution

I hope this Number of Islands LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

**More Coding Solutions >>**