1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
number-of-distinct-islands.cpp 1.13 KB
一键复制 编辑 原始数据 按行查看 历史
// Time: O(m * n)
// Space: O(m * n)
class Solution {
public:
int numDistinctIslands(vector<vector<int>>& grid) {
unordered_set<string> islands;
for (int i = 0; i < grid.size(); ++i) {
for (int j = 0; j < grid[0].size(); ++j) {
string island;
if (dfs(i, j, &grid, &island)) {
islands.emplace(island);
}
}
}
return islands.size();
}
private:
bool dfs(const int i, const int j,
vector<vector<int>> *grid, string *island) {
static const unordered_map<char, pair<int, int>>
directions = { {'l', {-1, 0} }, {'r', { 1, 0} },
{'u', { 0, 1} }, {'d', { 0, -1} }};
if (i < 0 || i >= grid->size() ||
j < 0 || j >= (*grid)[0].size() ||
(*grid)[i][j] <= 0) {
return false;
}
(*grid)[i][j] *= -1;
for (const auto& kvp : directions) {
island->push_back(kvp.first);
dfs(i + kvp.second.first, j + kvp.second.second, grid, island);
}
return true;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助