# 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**

*


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://code-snippets.hbamithkumara.com/leetcode/problems/101-200/number-of-islands.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
