Problem 748
Number of Distinct Islands
Medium · 20 pts · Matrix, Depth-First Search, Hash Table
Problem
In a binary grid, an island is a group of 1 cells connected horizontally or vertically. Two islands have the same shape if one can be moved onto the other by shifting it (translation only, no rotation or reflection). Count the number of distinct island shapes. Explore each island and record the positions of its cells relative to the island's first visited cell (or relative to its top-left corner); put these signatures in a set and print the set's size.
Input
The first line contains R and C. Each of the next R lines is a row of C characters 0 or 1.
Output
Print the number of distinct island shapes.
Constraints
1 <= R, C <= 500
Example input
4 5 11000 11000 00011 00011
Example output
1
Explanation
The grid 11000 / 11000 / 00011 / 00011 has two islands, each a 2 × 2 square. One can be shifted exactly onto the other, so there is only 1 distinct shape.