694. Number of Distinct Islands

Given a non-empty 2D array grid of 0's and 1's, 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.
Count the number of distinct islands. 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.
Example 1:

11000
11000
00011
00011

Given the above grid map, return 1.

Example 2:

11011
10000
00001
11011

Given the above grid map, return 3.

Notice that:

11
1

and

 1
11

are considered different island shapes, because we do not consider reflection / rotation.

Note: The length of each dimension in the given grid does not exceed 50.


這道題和LC200 Number of Islands一樣用DFS方法,重點(diǎn)在于如何記錄distinct islands shapes。

  1. 可以用字符串,記錄相對坐標(biāo)串。
  2. 可以用Integer,記錄相對坐標(biāo)串。
  3. 可以記錄path路徑,注意用0記錄進(jìn)出dfs函數(shù)的位置用以區(qū)分不同形狀。

比賽本應(yīng)該做出來,速度慢,也沒想出記錄存儲的好方法。

class Solution {
    ArrayList shape = new ArrayList<Integer>();
    public int numDistinctIslands(int[][] grid) {
        
        int n = grid.length;
        if(n==0) return 0;
        int m = grid[0].length;
        Set shapes = new HashSet<ArrayList<Integer>>();
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(grid[i][j]==1){
                    shape = new ArrayList<Integer>();
                    markAsZero(grid,i,j,0);
                    if(!shape.isEmpty()) shapes.add(shape);
                }
            }
        }
        return shapes.size();
    }
    
    public void markAsZero(int[][] grid, int i, int j, int path){
        if(i<0||j<0||i>=grid.length||j>=grid[0].length||grid[i][j]==0) return;
        
        grid[i][j]= 0;
        shape.add(path);
        markAsZero(grid,i-1,j,1);
        markAsZero(grid,i,j-1,2);
        markAsZero(grid,i+1,j,3);
        markAsZero(grid,i,j+1,4);
        shape.add(0);
        return;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1. 字段拆分 菜單法:數(shù)據(jù)-分列 分列第一步選擇合適文件類型:固定寬度; 鼠標(biāo)單擊要截取的字段,雙擊取消截取; ...
    掃地阿偉閱讀 881評論 0 1
  • 畢業(yè)的日子,正向我們一步步邁進(jìn), 我們將離別在蒼茫夏日。 燦爛的操場, 留存了我們曾經(jīng)灑下的汗水; 明朗的教室, ...
    安安毛毛閱讀 415評論 0 0
  • 原諒現(xiàn)在的我一身煙味, 原諒現(xiàn)在的我不知所謂, 原諒我現(xiàn)在仍是毫無長進(jìn), 原諒我只是重新想起你, 卻沒能重新找回你...
    未疚鹿葵閱讀 158評論 0 0

友情鏈接更多精彩內(nèi)容