首页 > 数据库 >[Oracle] LeetCode 694 Number of Distinct Islands 标记路线的DFS

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

时间:2022-10-26 06:55:05浏览次数:45  
标签:set 694 Distinct island Number DFS int grid

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();
    }
};

标签:set,694,Distinct,island,Number,DFS,int,grid
From: https://www.cnblogs.com/xinyu04/p/16827018.html

相关文章