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
|
#include <vector>
#include <set>
using namespace std;
class Solution {
public:
void dfs(vector<vector<int>>& grid, int x, int y, int baseX, int baseY, 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-baseX, y-baseY});
dfs(grid,x+1,y,baseX,baseY,shape);
dfs(grid,x-1,y,baseX,baseY,shape);
dfs(grid,x,y+1,baseX,baseY,shape);
dfs(grid,x,y-1,baseX,baseY,shape);
}
int numDistinctIslands(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,i,j,shape);
shapes.insert(shape);
}
return shapes.size();
}
};
|