# 1905. Count Sub Islands

```
T: O(mn)
S: O(mn)
```

```java
class Solution {
    private static final int[][] DIRECTIONS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    public int countSubIslands(int[][] grid1, int[][] grid2) {
        int m = grid1.length;
        int n = grid1[0].length;

        int count = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid2[i][j] == 1) {
                    Boolean[] result = new Boolean[1];
                    dfs(i, j, grid2, grid1, result);
                    if (result[0] == null) {
                        count++;
                    }
                }
            }
        }

        return count;
    }
    private void dfs(int i, int j, int[][] grid, int[][] grid1, Boolean[] result) {
        int m = grid.length;
        int n = grid[0].length;
        if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) {
            return;
        }
        if (grid1[i][j] == 0 && result[0] == null) {
            result[0] = false;
        }
        grid[i][j] = 0;
        for (int[] dir : DIRECTIONS) {
            dfs(i + dir[0], j + dir[1], grid, grid1, result);
        }
    }
}

/**
record all
sub-island position for island

then use position to see if there's 0 in (x, y)


use a result[0] to save the result (but entire island still need to traverse over and mark to 0!)

T: O(mn)
S: O(mn)
 */
```


---

# 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/dfs/1905.-count-sub-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.
