Number of Distinct Islands

Pattern: Grid graphs

medium

Two islands are the same when one can be shifted onto the other (no rotation or reflection). Record each island as the list of its cells relative to the first cell found, and count the different lists in a set.

The problem

Given a grid of 1 (land) and 0 (water), return the number of distinct island shapes, where two islands are the same if one is a translation of the other. LeetCode's version is premium.

Think first

  • What makes two islands the same?
  • How can you describe a shape independently of where it is?
  • Does the order of cells in the description matter?

Hints

    Brute force, and why it fails

    Compare every pair of islands cell by cell: O(k² × size).

    The key insight

    A position-free description lets a hash set count shapes in one pass.

    Dry run

    Grid with two 2 × 2 blocks of land. The first block's cells relative to (0, 0): (0, 0), (0, 1), (1, 0), (1, 1).

    Step 1 of 3

    The plan

    for each new island: collect (r - r0, c - c0) for its cells; sort; add to a set
    return the set's size
    

    Complexity

    Time
    O(R × C log(R × C))
    Space
    O(R × C)

    Each cell once, plus sorting each island's offsets.

    Edge cases

    • A 1 × 1 grid.
    • A grid with no land (or no walls).
    • Everything connected.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int numDistinctIslands(int[][] grid) {
            Set<String> shapes = new HashSet<>();
            for (int r = 0; r < grid.length; r++)
                for (int c = 0; c < grid[0].length; c++)
                    if (grid[r][c] == 1) {
                        List<int[]> cells = new ArrayList<>();
                        collect(grid, r, c, r, c, cells);   // cells relative to the island's first cell
                        StringBuilder key = new StringBuilder();
                        for (int[] p : cells) key.append(p[0]).append(',').append(p[1]).append(';');
                        shapes.add(key.toString());        // the same shape always gives the same key
                    }
            return shapes.size();
        }
    
        private void collect(int[][] g, int r, int c, int r0, int c0, List<int[]> cells) {
            if (r < 0 || c < 0 || r >= g.length || c >= g[0].length || g[r][c] != 1) return;
            g[r][c] = 0;
            cells.add(new int[]{r - r0, c - c0});
            collect(g, r + 1, c, r0, c0, cells); collect(g, r - 1, c, r0, c0, cells);
            collect(g, r, c + 1, r0, c0, cells); collect(g, r, c - 1, r0, c0, cells);
        }
    }

    C++

    class Solution {
    public:
        int numDistinctIslands(vector<vector<int>>& grid) {
            set<vector<pair<int, int>>> shapes;
            for (int r = 0; r < static_cast<int>(grid.size()); r++)
                for (int c = 0; c < static_cast<int>(grid[0].size()); c++)
                    if (grid[r][c] == 1) {
                        vector<pair<int, int>> cells;
                        collect(grid, r, c, r, c, cells);   // cells relative to the island's first cell
                        shapes.insert(cells);               // the same shape always gives the same list
                    }
            return static_cast<int>(shapes.size());
        }
    
        void collect(vector<vector<int>>& g, int r, int c, int r0, int c0, vector<pair<int, int>>& cells) {
            if (r < 0 || c < 0 || r >= static_cast<int>(g.size()) || c >= static_cast<int>(g[0].size()) || g[r][c] != 1) return;
            g[r][c] = 0;
            cells.push_back(make_pair(r - r0, c - c0));
            collect(g, r + 1, c, r0, c0, cells); collect(g, r - 1, c, r0, c0, cells);
            collect(g, r, c + 1, r0, c0, cells); collect(g, r, c - 1, r0, c0, cells);
        }
    };

    Python

    class Solution:
        def numDistinctIslands(self, grid: list[list[int]]) -> int:
            R, C, shapes = len(grid), len(grid[0]), set()
            for r in range(R):
                for c in range(C):
                    if grid[r][c] == 1:
                        cells, st = [], [(r, c)]
                        grid[r][c] = 0
                        while st:
                            a, b = st.pop()
                            cells.append((a - r, b - c))   # cells relative to the island's first cell
                            for x, y in ((a + 1, b), (a - 1, b), (a, b + 1), (a, b - 1)):
                                if 0 <= x < R and 0 <= y < C and grid[x][y] == 1:
                                    grid[x][y] = 0
                                    st.append((x, y))
                        shapes.add(tuple(sorted(cells)))   # the same shape always gives the same key
            return len(shapes)

    Common mistakes

    • Using absolute positions.
    • Treating rotated islands as equal.

    Similar problems