# 200. Number of Islands (BFS)

![](/files/-Mj9zeaVvNInmViW_R9w)

![](/files/-Mj9zgtJtVFZTSWT7V3U)

time: O(m\*n)

space:O(min(m,n))

```java
class Solution {
    private int[][] directions = {{0,1}, {1,0}, {0,-1}, {-1,0}};
    public int numIslands(char[][] grid) {
        
        int m = grid.length;
        int n = grid[0].length;
        int count = 0;
        boolean vistited[][] = new boolean[m][n];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1' && !vistited[i][j]) {
                    BFS(grid, i , j, vistited);
                    count++;
                }
            }
        }
        return count;
    }
    private void BFS(char[][] grid, int x , int y, boolean vistited[][]) {
                
        Queue<int[]> queue = new ArrayDeque<>();
        queue.offer(new int[]{x, y});
        vistited[x][y] = true;
        
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++ ) {
                int cor[] = queue.poll();
                int corX = cor[0];
                int corY = cor[1];
                for (int direction[] : directions) {
                    int newCorX = corX + direction[0];
                    int newCorY = corY + direction[1];
                    if (isValid(grid, vistited, newCorX, newCorY)) {
                        queue.offer(new int[]{newCorX, newCorY});
                        vistited[newCorX][newCorY] = true;
                    }
                }
            }
            
        }
    }
    private boolean isValid(char[][] grid, boolean vistited[][], int x, int y) {
        return (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && !vistited[x][y] && grid[x][y] == '1');
    }
}
```


---

# 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://timmybeeflin.gitbook.io/cracking-leetcode/dfs-and-bfs/bfs/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.
