leetcode 694 不同的岛屿数量

 

不同的岛屿数量

 

 其中有四个岛屿,但是左下角和右上角的岛屿形状相同,所以不同的岛屿共有三个,算法返回 3。

考点:

1. DFS

2. 序列化

3. 去重操作

public class Solution {
    /**
     * @param grid: a list of lists of integers
     * @return: return an integer, denote the number of distinct islands
     */
    public int numberofDistinctIslands(int[][] grid) {
        // write your code here
        int m = grid.length;
        int n = grid[0].length;
        HashSet<String> islands = new HashSet<>();
        for(int i = 0; i< m; i++){
            for(int j = 0; j<n;j++){
                if(grid[i][j] == 1){
                    StringBuilder sb = new StringBuilder();
                    dfs(grid, i, j, sb, 0);
                    islands.add(sb.toString());
                }
            }
        }
        return islands.size();

    }
    private void dfs(int[][] grid , int i , int j , StringBuilder sb, int dir){
        int m = grid.length;
        int n = grid[0].length;
        if (i < 0 || j < 0 || i >= m||j>= n || grid[i][j] == 0){
            return;
        }
        grid[i][j] = 0;
        sb.append(dir).append(',');
        dfs(grid,i-1,j,sb,1);//
        dfs(grid,i+1,j,sb,2);//
        dfs(grid,i,j-1,sb,3);//
        dfs(grid, i, j+1, sb, 4);//
        sb.append(-dir).append(',');
    }
}

 

posted @ 2022-04-04 09:49  zhongweiLeex  阅读(281)  评论(0编辑  收藏  举报