Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Graphs

Number of Distinct Islands

Medium · Graphs · Asked at Amazon, Microsoft, Google

In a grid of 0s and 1s, an island is a group of 1s connected up, down, left or right. Two islands are the same if one can be shifted (moved without rotating or flipping) to exactly cover the other. Print the number of distinct islands.

Input

First line: r c. Next r lines: c values (0 or 1).

Output

The number of distinct island shapes.

Constraints

Describe each island by the positions of its cells relative to its first cell (in scan order), sorted. Put these descriptions into a hash set; its size is the answer.

Example 1

Input

4 5
1 1 0 0 0
1 1 0 0 0
0 0 0 1 1
0 0 0 1 1

Output

1

Example 2

Input

4 5
1 1 0 1 1
1 0 0 0 0
0 0 0 0 1
1 1 0 1 1

Output

3

Hints

  1. Two islands match when their cells have the same positions relative to a fixed reference cell.
  2. Use the first cell found in the scan (top-most, then left-most) as the reference.
  3. Turn the sorted relative positions into a key and count distinct keys.

Approach

Scan the grid in row-major order; the first cell of an island you meet is its top-left-most cell, the same reference for any shifted copy. Flood fill the island, recording (row − r0, col − c0) for each cell. Sort the offsets (the visiting order can differ between copies) and insert the resulting list into a set. The set's size is the number of distinct shapes.

Complexity: O(r · c · log(r · c)) time · O(r · c) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int R, C;
    cin >> R >> C;
    vector<vector<int>> g(R, vector<int>(C));
    for (auto &row : g)
        for (auto &x : row) cin >> x;
    set<vector<int>> shapes;
    int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
    for (int i = 0; i < R; i++)
        for (int j = 0; j < C; j++) {
            if (g[i][j] != 1) continue;
            vector<int> cells;
            vector<pair<int, int>> st = {{i, j}};
            g[i][j] = 2;
            while (!st.empty()) {
                auto _b = st.back();
                auto x = _b.first;
                auto y = _b.second;
                st.pop_back();
                cells.push_back((x - i) * 1000 + (y - j));
                for (int d = 0; d < 4; d++) {
                    int a = x + dx[d], b = y + dy[d];
                    if (a >= 0 && b >= 0 && a < R && b < C && g[a][b] == 1) {
                        g[a][b] = 2;
                        st.push_back({a, b});
                    }
                }
            }
            sort(cells.begin(), cells.end());
            shapes.insert(cells);
        }
    cout << shapes.size() << "\n";
    return 0;
}

Python solution

import sys

data = sys.stdin.buffer.read().split()
R, C = int(data[0]), int(data[1])
g = [list(map(int, data[2 + i * C : 2 + (i + 1) * C])) for i in range(R)]
shapes = set()
for i in range(R):
    for j in range(C):
        if g[i][j] != 1:
            continue
        cells = []
        stack = [(i, j)]
        g[i][j] = 2
        while stack:
            x, y = stack.pop()
            cells.append((x - i, y - j))
            for a, b in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
                if 0 <= a < R and 0 <= b < C and g[a][b] == 1:
                    g[a][b] = 2
                    stack.append((a, b))
        shapes.add(tuple(sorted(cells)))
print(len(shapes))

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int R = (int) in.nval;
        in.nextToken();
        int C = (int) in.nval;
        int[][] g = new int[R][C];
        for (int i = 0; i < R; i++)
            for (int j = 0; j < C; j++) {
                in.nextToken();
                g[i][j] = (int) in.nval;
            }
        int[] dx = {1, -1, 0, 0}, dy = {0, 0, 1, -1};
        HashSet<String> shapes = new HashSet<>();
        for (int i = 0; i < R; i++)
            for (int j = 0; j < C; j++) {
                if (g[i][j] != 1) continue;
                ArrayList<Integer> cells = new ArrayList<>();
                ArrayDeque<int[]> st = new ArrayDeque<>();
                st.push(new int[] {i, j});
                g[i][j] = 2;
                while (!st.isEmpty()) {
                    int[] c = st.pop();
                    cells.add((c[0] - i) * 1000 + (c[1] - j));
                    for (int d = 0; d < 4; d++) {
                        int a = c[0] + dx[d], b = c[1] + dy[d];
                        if (a >= 0 && b >= 0 && a < R && b < C && g[a][b] == 1) {
                            g[a][b] = 2;
                            st.push(new int[] {a, b});
                        }
                    }
                }
                Collections.sort(cells);
                shapes.add(cells.toString());
            }
        System.out.println(shapes.size());
    }
}

Solve Number of Distinct Islands online · All practice problems