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
|
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
class Solution {
public:
void dfs(vector<vector<int>>& grid, int x, int y, vector<pair<int,int>>& shape) {
int m = grid.size(), n = grid[0].size();
if (x<0||y<0||x>=m||y>=n||grid[x][y]==0) return;
grid[x][y]=0;
shape.push_back({x, y});
dfs(grid,x+1,y,shape);
dfs(grid,x-1,y,shape);
dfs(grid,x,y+1,shape);
dfs(grid,x,y-1,shape);
}
vector<vector<pair<int,int>>> transforms(const vector<pair<int,int>>& shape) {
vector<vector<pair<int,int>>> res(8);
for (auto& p : shape) {
int x = p.first, y = p.second;
res[0].push_back({ x, y });
res[1].push_back({ x, -y });
res[2].push_back({ -x, y });
res[3].push_back({ -x, -y });
res[4].push_back({ y, x });
res[5].push_back({ y, -x });
res[6].push_back({ -y, x });
res[7].push_back({ -y, -x });
}
for (auto& v : res) {
sort(v.begin(), v.end());
int ox = v[0].first, oy = v[0].second;
for (auto& p : v) { p.first -= ox; p.second -= oy; }
}
return res;
}
int numDistinctIslands2(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
set<vector<pair<int,int>>> shapes;
for (int i=0;i<m;++i) for (int j=0;j<n;++j) if (grid[i][j]) {
vector<pair<int,int>> shape;
dfs(grid,i,j,shape);
auto all = transforms(shape);
shapes.insert(*min_element(all.begin(), all.end()));
}
return shapes.size();
}
};
|