Saturday, October 7, 2017
694. Number of Distinct Islands
void dfs(vector<vector<int>>& grid, int i, int j, char d, string& trace) {
int NI = grid.size();
int NJ = grid[0].size();
if(i<0 || i>=NI || j<0 || j>=NJ || grid[i][j] == 0) {
trace += '0';
return;
}
grid[i][j] = 0;
trace += d;
dfs(grid, i, j+1, 'e', trace);
dfs(grid, i+1, j, 'n', trace);
dfs(grid, i, j-1, 'w', trace);
dfs(grid, i-1, j, 's', trace);
}
int numDistinctIslands(vector<vector<int>>& grid) {
if(grid.size() == 0) return 0;
int NI = grid.size();
int NJ = grid[0].size();
unordered_map<string, int> mp;
for(int i=0; i<NI; i++) {
for(int j=0; j<NJ; j++) {
if(grid[i][j]) {
string trace = "";
dfs(grid, i, j, 'c', trace);
if(trace.size() != 0)
mp[trace]++;
}
}
}
return mp.size();
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment