> For the complete documentation index, see [llms.txt](https://code-snippets.hbamithkumara.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://code-snippets.hbamithkumara.com/leetcode/problems/101-200/number-of-islands.md).

# 200. 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.

### Constraints

### Approach

### Links

* [GeeksforGeeks](https://www.geeksforgeeks.org/find-number-of-islands/)
* [Leetcode](https://leetcode.com/problems/number-of-islands/)
* [ProgramCreek](https://www.programcreek.com/2014/04/leetcode-number-of-islands-java/)
* YouTube

### **Examples**

{% tabs %}
{% tab title="Example 1" %}
**Input:** grid = \[

\["1", "1", "1", "1", "0"],

\["1", "1", "0", "1", "0"],

\["1", "1", "0", "0", "0"],

\["0", "0", "0", "0", "0"]

]&#x20;

**Output:** 1
{% endtab %}

{% tab title="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
{% endtab %}
{% endtabs %}

### **Solutions**

{% tabs %}
{% tab title="Solution 1" %}

```java
/**
 * Time complexity : O(M*N), Where M is row size and N is column size
 * Space complexity : O(1)
 */

class Solution {
    public int numIslands(char[][] grid) {
        if(grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        
        int row = grid.length;
        int col = grid[0].length;
        
        int count = 0;
        for(int i = 0; i < row; i++) {
            for(int j = 0; j < col; j++) {
                if(grid[i][j] == '1') {
                    count++;
                    merge(grid, row, col, i, j);
                }
            }
        }
        return count;
    }
    
    private void merge(char[][] grid, int row, int col, int i, int j) {
        if(i < 0 || i >= row || j < 0 || j >= col) return;
        
        if(grid[i][j] != '1') return;
        
        grid[i][j] = 'X';
        
        merge(grid, row, col, i-1, j);
        merge(grid, row, col, i+1, j);
        merge(grid, row, col, i, j-1);
        merge(grid, row, col, i, j+1);
    }
}
```

{% endtab %}
{% endtabs %}

### **Follow up**

*
