forked from profpiyush/Hacktberfest-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Leetcode Number of Distinct islands II.java
67 lines (59 loc) · 2.13 KB
/
Leetcode Number of Distinct islands II.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class Solution {
int[][] grid;
boolean[][] seen;
ArrayList<Integer> shape;
public void explore(int r, int c) {
if (0 <= r && r < grid.length && 0 <= c && c < grid[0].length &&
grid[r][c] == 1 && !seen[r][c]) {
seen[r][c] = true;
shape.add(r * grid[0].length + c);
explore(r+1, c);
explore(r-1, c);
explore(r, c+1);
explore(r, c-1);
}
}
public String canonical(ArrayList<Integer> shape) {
String ans = "";
int lift = grid.length + grid[0].length;
int[] out = new int[shape.size()];
int[] xs = new int[shape.size()];
int[] ys = new int[shape.size()];
for (int c = 0; c < 8; ++c) {
int t = 0;
for (int z: shape) {
int x = z / grid[0].length;
int y = z % grid[0].length;
//x y, x -y, -x y, -x -y
//y x, y -x, -y x, -y -x
xs[t] = c<=1 ? x : c<=3 ? -x : c<=5 ? y : -y;
ys[t++] = c<=3 ? (c%2==0 ? y : -y) : (c%2==0 ? x : -x);
}
int mx = xs[0], my = ys[0];
for (int x: xs) mx = Math.min(mx, x);
for (int y: ys) my = Math.min(my, y);
for (int j = 0; j < shape.size(); ++j) {
out[j] = (xs[j] - mx) * lift + (ys[j] - my);
}
Arrays.sort(out);
String candidate = Arrays.toString(out);
if (ans.compareTo(candidate) < 0) ans = candidate;
}
return ans;
}
public int numDistinctIslands2(int[][] grid) {
this.grid = grid;
seen = new boolean[grid.length][grid[0].length];
Set shapes = new HashSet<String>();
for (int r = 0; r < grid.length; ++r) {
for (int c = 0; c < grid[0].length; ++c) {
shape = new ArrayList();
explore(r, c);
if (!shape.isEmpty()) {
shapes.add(canonical(shape));
}
}
}
return shapes.size();
}
}