Skip to content

Commit 5039fcb

Browse files
authored
Create number-of-distinct-islands.cpp
1 parent dcfbc08 commit 5039fcb

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

C++/number-of-distinct-islands.cpp

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Time: O(m * n)
2+
// Space: O(m * n)
3+
4+
class Solution {
5+
public:
6+
int numDistinctIslands(vector<vector<int>>& grid) {
7+
unordered_set<string> islands;
8+
for (int i = 0; i < grid.size(); ++i) {
9+
for (int j = 0; j < grid[0].size(); ++j) {
10+
string island;
11+
if (dfs(i, j, &grid, &island)) {
12+
islands.emplace(island);
13+
}
14+
}
15+
}
16+
return islands.size();
17+
}
18+
19+
private:
20+
21+
bool dfs(const int i, const int j,
22+
vector<vector<int>> *grid, string *island) {
23+
static const unordered_map<char, pair<int, int>>
24+
directions = { {'l', {-1, 0} }, {'r', { 1, 0} },
25+
{'u', { 0, 1} }, {'d', { 0, -1} }};
26+
27+
if (i < 0 || i >= grid->size() ||
28+
j < 0 || j >= (*grid)[0].size() ||
29+
(*grid)[i][j] <= 0) {
30+
return false;
31+
}
32+
(*grid)[i][j] *= -1;
33+
for (const auto& kvp : directions) {
34+
island->push_back(kvp.first);
35+
dfs(i + kvp.second.first, j +kvp.second.second, grid, island);
36+
}
37+
return true;
38+
}
39+
};

0 commit comments

Comments
 (0)