Number of Distinct Islands
Medium
Topics
You are given an m x n binary matrix grid. An island is a group of 1s connected 4-directionally (up, down, left, right). You may assume all four edges of the grid are surrounded by water.
Two islands are considered the same if one can be translated (slid horizontally and/or vertically) to equal the other. Rotations and reflections do not count as the same.
Return the number of distinct islands.
Example 1
Input: grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]] Output: 1 Explanation: Both islands are 2x2 blocks, so sliding one onto the other matches it exactly.
Example 2
Input: grid = [[1,1,0,1,1],[1,0,0,0,0],[0,0,0,0,1],[1,1,0,1,1]] Output: 3 Explanation: Four islands, but the horizontal pair in the top right and the horizontal pair in the bottom left are the same shape.
Example 3
Input: grid = [[0,0,0],[0,0,0]] Output: 0 Explanation: No land at all.
Constraints
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 50
- grid[i][j] is either 0 or 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
Counting islands is the easy half — the hard half is deciding when two of them are the same island shape. Absolute coordinates cannot answer that, because the same shape in two places has two different coordinate sets.
What survives translation is the set of offsets within an island. Pin each island to its own top-left corner and every copy of that shape, wherever it sits in the grid, produces an identical set of offsets. So the question becomes: how many different offset sets are there?
Because only translation counts and not rotation, there is no need to try the eight orientations of each shape — one canonical form per island is enough.
Approach
- Sweep the grid. On each unvisited
1, collect the whole island’s cells and mark them visited so no cell is counted twice. - Find the island’s minimum row and minimum column, and subtract them from every cell. That pins the island to the origin regardless of where it sat.
- Sort the resulting offsets so the same shape always yields the same sequence, and join them into one string key.
- Add each key to a set. The set’s size is the answer.
Walkthrough
grid = [[1,1,0,1,1],
[1,0,0,0,0],
[0,0,0,0,1],
[1,1,0,1,1]]
island cells min row/col offsets (sorted)
(0,0)(0,1)(1,0) 0,0 (0,0)(0,1)(1,0)
(0,3)(0,4) 0,3 (0,0)(0,1)
(2,4)(3,3)(3,4) 2,3 (0,1)(1,0)(1,1)
(3,0)(3,1) 3,0 (0,0)(0,1)
keys seen: 3 distinct (rows 2 and 4 share one)
answer 3Complexity
- Time — O(m * n * log(m * n)): every cell is visited once, and each island’s offsets are sorted; across all islands that is at most one sort of every land cell.
- Space — O(m * n): the visited matrix, plus the stored keys, which together hold at most one entry per land cell.
Common Pitfalls
- Pinning to the first cell the traversal happens to reach rather than to the minimum row and column. Those differ when an island’s top row starts further right than a lower row, and the key then depends on where the sweep entered the island.
- Leaving the offsets unsorted, which makes the key depend on traversal order — a depth-first and a breadth-first walk over the same shape would then disagree.
- Treating diagonal neighbours as connected. The statement says 4-directionally, and allowing 8 merges islands that should stay separate.
Full Solution — all languages
class Solution:
def numDistinctIslands(self, grid):
rows, cols = len(grid), len(grid[0])
seen = [[False] * cols for _ in range(rows)]
shapes = set()
for r in range(rows):
for c in range(cols):
if grid[r][c] != 1 or seen[r][c]:
continue
cells, stack = [], [(r, c)]
seen[r][c] = True
while stack:
y, x = stack.pop()
cells.append((y, x))
for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
ny, nx = y + dy, x + dx
if 0 <= ny < rows and 0 <= nx < cols and grid[ny][nx] == 1 and not seen[ny][nx]:
seen[ny][nx] = True
stack.append((ny, nx))
base_r = min(y for y, _ in cells)
base_c = min(x for _, x in cells)
shapes.add(tuple(sorted((y - base_r, x - base_c) for y, x in cells)))
return len(shapes)import java.util.*;
class Solution {
public int numDistinctIslands(int[][] grid) {
int rows = grid.length, cols = grid[0].length;
boolean[][] seen = new boolean[rows][cols];
int[][] D = { {
1, 0
},
{
-1, 0
},
{
0, 1
},
{
0, -1
}
};
Set<String> shapes = new HashSet<>();
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] != 1 || seen[r][c]) continue;
List<int[]> cells = new ArrayList<>();
Deque<int[]> stack = new ArrayDeque<>();
stack.push(new int[]{r, c});
seen[r][c] = true;
while (!stack.isEmpty()) {
int[] cur = stack.pop();
cells.add(cur);
for (int[] d : D) {
int ny = cur[0] + d[0], nx = cur[1] + d[1];
if (ny < 0 || ny >= rows || nx < 0 || nx >= cols) continue;
if (grid[ny][nx] != 1 || seen[ny][nx]) continue;
seen[ny][nx] = true;
stack.push(new int[]{ny, nx});
}
}
int br = Integer.MAX_VALUE, bc = Integer.MAX_VALUE;
for (int[] p : cells) {
br = Math.min(br, p[0]);
bc = Math.min(bc, p[1]);
}
List<int[]> off = new ArrayList<>();
for (int[] p : cells) off.add(new int[]{p[0] - br, p[1] - bc});
off.sort((x, y) -> x[0] != y[0] ? x[0] - y[0] : x[1] - y[1]);
StringBuilder key = new StringBuilder();
for (int[] p : off) key.append(p[0]).append(',').append(p[1]).append(';');
shapes.add(key.toString());
}
}
return shapes.size();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int numDistinctIslands(vector<vector<int>>& grid) {
int rows = grid.size(), cols = grid[0].size();
vector<vector<bool>> seen(rows, vector<bool>(cols, false));
int D[4][2] = { {
1, 0
},
{
-1, 0
},
{
0, 1
},
{
0, -1
}
};
set<string> shapes;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] != 1 || seen[r][c]) continue;
vector<pair<int, int>> cells, stk;
stk.push_back({r, c});
seen[r][c] = true;
while (!stk.empty()) {
pair<int, int> cur = stk.back();
stk.pop_back();
cells.push_back(cur);
for (auto& d : D) {
int ny = cur.first + d[0], nx = cur.second + d[1];
if (ny < 0 || ny >= rows || nx < 0 || nx >= cols) continue;
if (grid[ny][nx] != 1 || seen[ny][nx]) continue;
seen[ny][nx] = true;
stk.push_back({ny, nx});
}
}
int br = cells[0].first, bc = cells[0].second;
for (auto& p : cells) {
br = min(br, p.first);
bc = min(bc, p.second);
}
vector<pair<int, int>> off;
for (auto& p : cells) off.push_back({p.first - br, p.second - bc});
sort(off.begin(), off.end());
string key;
for (auto& p : off) key += to_string(p.first) + "," + to_string(p.second) + ";";
shapes.insert(key);
}
}
return (int)shapes.size();
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var numDistinctIslands = function(grid) {
const rows = grid.length, cols = grid[0].length;
const seen = Array.from({ length: rows }, () => new Array(cols).fill(false));
const D = [[1, 0], [-1, 0], [0, 1], [0, -1]];
const shapes = new Set();
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] !== 1 || seen[r][c]) continue;
const cells = [], stack = [[r, c]];
seen[r][c] = true;
while (stack.length) {
const cur = stack.pop();
cells.push(cur);
for (const d of D) {
const ny = cur[0] + d[0], nx = cur[1] + d[1];
if (ny < 0 || ny >= rows || nx < 0 || nx >= cols) continue;
if (grid[ny][nx] !== 1 || seen[ny][nx]) continue;
seen[ny][nx] = true;
stack.push([ny, nx]);
}
}
let br = cells[0][0], bc = cells[0][1];
for (const p of cells) {
br = Math.min(br, p[0]);
bc = Math.min(bc, p[1]);
}
const key = cells.map(p => [p[0] - br, p[1] - bc]) .sort((a, b) => a[0] - b[0] || a[1] - b[1]) .map(p => p[0] + ',' + p[1]).join(';');
shapes.add(key);
}
}
return shapes.size;
};