[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
我们在 过程中,用一个路径 来记录遍历的顺序,然后放进 里面
点击查看代码
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(); } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理