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 00011Given the above grid map, return
1
.
11 1and
1 11are 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:
11100 10001 01001 01110Given the above grid map, return
2
.111 1and
1 1
111 1and
1 111are considered same island shapes. Because if we flip the first array in the up/down direction, then they have the same shapes.
Note:
The length of each dimension in the given grid
does not exceed 50.
Intuition
\nAs in Approach #1 to the sister problem Number of Distinct Islands, we determine local coordinates for each island.
\nAfterwards, we will rotate and reflect the coordinates about the origin and translate the shape so that the bottom-left-most coordinate is (0, 0). At the end, the smallest of these lists coordinates will be the canonical representation of the shape.
\nAlgorithm
\nWe feature two different implementations, but the core idea is the same. We start with the code from the previous problem, Number of Distinct Islands.
\nFor each of 8 possible rotations and reflections of the shape, we will perform the transformation and then translate the shape so that the bottom-left-most coordinate is (0, 0). Afterwards, we will consider the canonical hash of the shape to be the maximum of these 8 intermediate hashes.
\nIn Python, the motivation to use complex numbers is that rotation by 90 degrees is the same as multiplying by the imaginary unit, 1j
. In Java, we manipulate the coordinates directly. The 8 rotations and reflections of each point are (x, y), (-x, y), (x, -y), (-x, -y), (y, x), (-y, x), (y, -x), (-y, -x)
.
Python
\nclass Solution(object):\n def numDistinctIslands2(self, grid):\n seen = set()\n def explore(r, c):\n if (0 <= r < len(grid) and 0 <= c < len(grid[0]) and\n grid[r][c] and (r, c) not in seen):\n seen.add((r, c))\n shape.add(complex(r, c))\n explore(r+1, c)\n explore(r-1, c)\n explore(r, c+1)\n explore(r, c-1)\n\n def canonical(shape):\n def translate(shape):\n w = complex(min(z.real for z in shape),\n min(z.imag for z in shape))\n return sorted(str(z-w) for z in shape)\n\n ans = None\n for k in xrange(4):\n ans = max(ans, translate([z * (1j)**k for z in shape]))\n ans = max(ans, translate([complex(z.imag, z.real) * (1j)**k\n for z in shape]))\n return tuple(ans)\n\n shapes = set()\n for r in range(len(grid)):\n for c in range(len(grid[0])):\n shape = set()\n explore(r, c)\n if shape:\n shapes.add(canonical(shape))\n\n return len(shapes)\n
Java
\nclass Solution {\n int[][] grid;\n boolean[][] seen;\n ArrayList<Integer> shape;\n\n public void explore(int r, int c) {\n if (0 <= r && r < grid.length && 0 <= c && c < grid[0].length &&\n grid[r][c] == 1 && !seen[r][c]) {\n seen[r][c] = true;\n shape.add(r * grid[0].length + c);\n explore(r+1, c);\n explore(r-1, c);\n explore(r, c+1);\n explore(r, c-1);\n }\n }\n\n public String canonical(ArrayList<Integer> shape) {\n String ans = "";\n int lift = grid.length + grid[0].length;\n int[] out = new int[shape.size()];\n int[] xs = new int[shape.size()];\n int[] ys = new int[shape.size()];\n\n for (int c = 0; c < 8; ++c) {\n int t = 0;\n for (int z: shape) {\n int x = z / grid[0].length;\n int y = z % grid[0].length;\n //x y, x -y, -x y, -x -y\n //y x, y -x, -y x, -y -x\n xs[t] = c<=1 ? x : c<=3 ? -x : c<=5 ? y : -y;\n ys[t++] = c<=3 ? (c%2==0 ? y : -y) : (c%2==0 ? x : -x);\n }\n\n int mx = xs[0], my = ys[0];\n for (int x: xs) mx = Math.min(mx, x);\n for (int y: ys) my = Math.min(my, y);\n\n for (int j = 0; j < shape.size(); ++j) {\n out[j] = (xs[j] - mx) * lift + (ys[j] - my);\n }\n Arrays.sort(out);\n String candidate = Arrays.toString(out);\n if (ans.compareTo(candidate) < 0) ans = candidate;\n }\n return ans;\n }\n\n public int numDistinctIslands2(int[][] grid) {\n this.grid = grid;\n seen = new boolean[grid.length][grid[0].length];\n Set shapes = new HashSet<String>();\n\n for (int r = 0; r < grid.length; ++r) {\n for (int c = 0; c < grid[0].length; ++c) {\n shape = new ArrayList();\n explore(r, c);\n if (!shape.isEmpty()) {\n shapes.add(canonical(shape));\n }\n }\n }\n\n return shapes.size();\n }\n}\n
Complexity Analysis
\nTime Complexity: , where is the number of rows in the given grid
, and is the number of columns. We visit every square once, and each square belongs to at most one shape. The log factor comes from sorting the shapes.
Space complexity: , the space used to keep track of the shapes.
\nAnalysis written by: @awice
\n