Number of Distinct Islands II (Hard Amazon)

update 2018-05-20 20:46:58

LeetCodearrow-up-right

Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Count the number of distinct islands. An island is considered to be the same as another if they have the same shape, or have the same shape after rotation (90, 180, or 270 degrees only) or reflection (left/right direction or up/down direction).

Example 1:

11000
10000
00001
00011
Given the above grid map, return 1. 

Notice that:

    11
    1
and
     1
    11
are considered same island shapes. Because if we make a 180 degrees clockwise rotation 
on the first island, then two islands will have the same shapes.

Example 2:

Notice that:

Note: The length of each dimension in the given grid does not exceed 50.

Basic Idea:

和之前的 Number of Distinct Islands 类似,这道题目也可以被分为两部分,一部分是获得所有的island点的集合,二是对每个 island 进行 serilization 生成唯一 hashCode 用于判断是否重复。

而这道题更加难的点在于其需要考虑到包括旋转和翻转在内的多种变换,解决办法就是先得到一个岛所有点的坐标集合,然后分别对其进行各种变换,变换之后进行标准化,使得 left 和 top 都为 0 ,然后对坐标list排序,然后序列化。而最终一个岛的hashCode就是所有变换后生成的string中字典顺序最大或者最小的,这样就能保证同样形状的岛有唯一的hashCode.

  • Java Code: