Count Sub Islands

Medium Graphs Matrix Graphs

Reported atX (Twitter)Zepto

Count Sub Islands is a medium graphs problem solved with the matrix graphs pattern. The best approach, optimal (bfs flood fill with a queue), runs in O(m · n) time and O(m · n) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from dfs flood fill with a covered flag up.

Problem

You are given two binary grids grid1 and grid2 of the same size m x n. In each grid, 1 is land and 0 is water, and an island is a group of land cells joined through their up, down, left or right neighbours (corners do not connect).

An island of grid2 is a sub-island if every one of its cells is also land in grid1. Return how many islands of grid2 are sub-islands.

Examples

Example 1

Input
grid1 = [[1,1,0,1,1],[1,1,0,0,1],[0,1,1,0,0],[1,0,1,1,1]], grid2 = [[1,1,0,0,1],[0,1,0,1,1],[0,0,1,0,0],[1,0,1,1,0]]
Output
3
Why
grid2 has four islands. The ones made of (0,0),(0,1),(1,1), of (3,0), and of (2,2),(3,2),(3,3) lie entirely on land of grid1. The island (0,4),(1,3),(1,4) is not a sub-island, because (1,3) is water in grid1.

Example 2

Input
grid1 = [[0,1],[1,1]], grid2 = [[1,1],[0,1]]
Output
0
Why
grid2 has one island of three cells. Its cell (0,0) is water in grid1, so the whole island fails, even though the other two cells are covered.

Example 3

Input
grid1 = [[1,1,1]], grid2 = [[1,0,1]]
Output
2
Why
grid2 has two single-cell islands, and both sit on land in grid1. It does not matter that grid1 joins them into one bigger island.

Constraints

  • m == grid1.length == grid2.length
  • n == grid1[i].length == grid2[i].length
  • 1 <= m, n <= 500
  • Every cell of both grids is 0 or 1.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
DFS flood fill with a covered flagO(m · n)O(m · n)
Optimal (BFS flood fill with a queue)O(m · n)O(m · n)

1DFS flood fill with a covered flag

TimeO(m · n)Every cell is flooded at most once, with four neighbour checks each.
SpaceO(m · n)The recursion can be as deep as the largest island, which can hold every cell of the grid.

Scan grid2. Each time you meet a land cell that has not been visited, flood its whole island with a recursive DFS, turning visited cells into water so they are never seen again. The DFS returns true only if every cell it visited is land in grid1. Count the islands for which it returns true.

  1. For every cell (r, c) with grid2[r][c] == 1, call dfs(r, c); if it returns true, increment the count.
  2. dfs returns true straight away for a cell outside the grid or already water in grid2.
  3. Otherwise it sets grid2[r][c] = 0, starts with sub = (grid1[r][c] == 1), and ANDs in the result of all four neighbours, always calling every one of them.
  4. Return the count.
class Solution {
    public int countSubIslands(int[][] grid1, int[][] grid2) {
        int m = grid2.length, n = grid2[0].length, count = 0;
        for (int r = 0; r < m; r++) {
            for (int c = 0; c < n; c++) {
                if (grid2[r][c] == 1 && dfs(grid1, grid2, r, c)) count++;
            }
        }
        return count;
    }

    private boolean dfs(int[][] grid1, int[][] grid2, int r, int c) {
        if (r < 0 || c < 0 || r >= grid2.length || c >= grid2[0].length || grid2[r][c] == 0) return true;
        grid2[r][c] = 0;
        boolean sub = grid1[r][c] == 1;
        sub &= dfs(grid1, grid2, r + 1, c);
        sub &= dfs(grid1, grid2, r - 1, c);
        sub &= dfs(grid1, grid2, r, c + 1);
        sub &= dfs(grid1, grid2, r, c - 1);
        return sub;
    }
}

2Optimal (BFS flood fill with a queue)

TimeO(m · n)Each cell is queued and polled at most once, with four neighbour checks each.
SpaceO(m · n)The queue can hold O(m · n) cells in the worst case; grid2 itself is reused as the visited marker.

The same scan and the same covered flag, but each island is flooded with a queue instead of recursion. A cell is turned into water the moment it is queued, so it is never queued twice, and the memory no longer depends on how deep a snake-shaped island goes.

  1. For every cell (r, c) with grid2[r][c] == 1, flood its island with bfs; if bfs returns true, increment the count.
  2. bfs sets the start cell to water, queues it and sets sub = true.
  3. Poll a cell; if grid1 has water there, set sub = false. For each in-grid neighbour that is land in grid2, set it to water and queue it.
  4. When the queue is empty, return sub. Return the count at the end.
class Solution {
    private static final int[][] DIRS = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };

    public int countSubIslands(int[][] grid1, int[][] grid2) {
        int m = grid2.length, n = grid2[0].length, count = 0;
        for (int r = 0; r < m; r++) {
            for (int c = 0; c < n; c++) {
                if (grid2[r][c] == 1 && bfs(grid1, grid2, r, c)) count++;
            }
        }
        return count;
    }

    private boolean bfs(int[][] grid1, int[][] grid2, int sr, int sc) {
        int m = grid2.length, n = grid2[0].length;
        Deque<int[]> queue = new ArrayDeque<>();
        grid2[sr][sc] = 0;
        queue.add(new int[] { sr, sc });
        boolean sub = true;
        while (!queue.isEmpty()) {
            int[] cell = queue.poll();
            int r = cell[0], c = cell[1];
            if (grid1[r][c] == 0) sub = false;
            for (int[] d : DIRS) {
                int x = r + d[0], y = c + d[1];
                if (x >= 0 && y >= 0 && x < m && y < n && grid2[x][y] == 1) {
                    grid2[x][y] = 0;
                    queue.add(new int[] { x, y });
                }
            }
        }
        return sub;
    }
}

Edge cases to test

  • grid2 has no land at all (answer 0)
  • An island of grid2 that is covered everywhere except one far-away cell
  • Several islands of grid2 sitting inside one island of grid1 (each counts separately)
  • A long snake-shaped island, where deep recursion can overflow the stack
  • Cells that touch only at a corner are not connected

Hints

Hint 1

Find the islands of grid2 the usual way, with a flood fill from every unvisited land cell.

Hint 2

While flooding one island, keep a flag that turns false the first time a cell is water in grid1.

Hint 3

Do not stop the flood early when the flag turns false. Finish marking the island, or its leftover cells would be counted as new islands later.

FAQ

What is the best time complexity for Count Sub Islands?

Optimal (BFS flood fill with a queue) runs in O(m · n) time and O(m · n) extra space. Each cell is queued and polled at most once, with four neighbour checks each.

Which pattern does Count Sub Islands use?

It is a graphs problem that uses the matrix graphs pattern. Other problems with the same pattern: Flood Fill, Maximum Number of Points From Grid Queries, Contain Virus.

Is there a brute force solution for Count Sub Islands?

Yes. DFS flood fill with a covered flag takes O(m · n) time and O(m · n) space. Scan grid2.

Which edge cases should I test for Count Sub Islands?

grid2 has no land at all (answer 0); An island of grid2 that is covered everywhere except one far-away cell; Several islands of grid2 sitting inside one island of grid1 (each counts separately); A long snake-shaped island, where deep recursion can overflow the stack; Cells that touch only at a corner are not connected.