xinyu04

导航

< 2025年3月 >
23 24 25 26 27 28 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 27 28 29
30 31 1 2 3 4 5

统计

[Oracle] LeetCode 694 Number of Distinct Islands 标记路线的DFS

You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

An island is considered to be the same as another if and only if one island can be translated (and not rotated or reflected) to equal the other.

Return the number of distinct islands.

Solution

我们在 DFS 过程中,用一个路径 s 来记录遍历的顺序,然后放进 set 里面

点击查看代码
class Solution {
private:
int dir[4][2]={
1,0,
0,1,
-1,0,
0,-1
};
vector<string> dr = {"d", "r","u","l"};
bool check(int x,int y, int r, int c){
if(x<0||y<0||x>=r||y>=c)return false;
return true;
}
unordered_set<string> st;
void dfs(int x,int y,int r,int c, vector<vector<int>>&grid, string& s){
grid[x][y]=2;
for(int i=0;i<4;i++){
int nx = x+dir[i][0], ny = y+dir[i][1];
if(check(nx,ny,r,c) && grid[nx][ny]==1){
s+=dr[i];
dfs(nx,ny,r,c,grid,s);
}
}
s+="E";
}
public:
int numDistinctIslands(vector<vector<int>>& grid) {
int r = grid.size(), c = grid[0].size();
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
if(grid[i][j]==1){
string tmp = "S";
dfs(i,j,r,c,grid, tmp);
cout<<tmp<<endl;
st.insert(tmp);
}
}
}
return st.size();
}
};

posted on   Blackzxy  阅读(15)  评论(0编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示