xinyu04

导航

[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 2022-10-26 06:44  Blackzxy  阅读(11)  评论(0编辑  收藏  举报