这个题用dfs 大家都能想到,重点是,如何描述岛的结构/形状。
我用的方法,是用字符来表明与所在陆地链接的陆地的位置,但是注意,做完dfs,一定要叫个‘b’,这样才能完整描述形状
C++ 代码
class Solution {
public:
int numDistinctIslands(vector<vector<int>>& grid) {
unordered_set<string> Result;
for (int i = 0; i < grid.size(); i++){
for (int j = 0; j < grid[0].size(); j++){
string path;
if (grid[i][j] == 1){
dfs(i, j, grid, path, 'c');
}
if (!path.empty()){
Result.insert(path);
}
}
}
return Result.size();
}
void dfs(int i, int j, vector<vector<int>>& grid, string& path, char dir){
if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() || grid[i][j] == 0){
return;
}
path.push_back(dir);
grid[i][j] = 0;
dfs(i-1, j, grid, path, 'u');
dfs(i+1, j, grid, path, 'd');
dfs(i, j-1, grid, path, 'l');
dfs(i, j+1, grid, path, 'r');
path.push_back('b');
}
};