[抄題]:算法
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.app
Example 1:ide
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:ui
11
1
andspa
1
11
are considered different island shapes, because we do not consider reflection / rotation.debug
[暴力解法]:code
時間分析:
空間分析:
[優化後]:
時間分析:
空間分析:
[奇葩輸出條件]:
[奇葩corner case]:
[思惟問題]:
不知道怎麼存一塊島嶼的形狀:其實就是存方向構成的string就好了
每次走過一個點,都要設置該點爲0,由於形狀只統計一次,不重複
[英文數據結構或算法,爲何不用別的數據結構或算法]:
[一句話思路]:
[輸入量]:空: 正常狀況:特大:特小:程序裏處理到的特殊狀況:異常狀況(不合法不合理的輸入):
[畫圖]:
DFS就是:走到底-到最後一行改變條件-沒出界就再走到底,反正就是走到底就對了
{1, 1, 0}, {0, 1, 1}, {0, 0, 0}, {1, 1, 1}, {0, 1, 0}
爲了分辨方向序列,加星號的位置不一樣。
curShape = rdr
curShape = rdr*
curShape = rdr**
curShape = rdr***
curShape = rd
curShape = rd*r
curShape = rd*r*
curShape = rd*r**
[一刷]:
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分鐘肉眼debug的結果]:
[總結]:
[複雜度]:Time complexity: O(mn) Space complexity: O(mn)
[算法思想:迭代/遞歸/分治/貪心]:
[關鍵模板化代碼]:
[其餘解法]:
[Follow Up]:
[LC給出的題目變變變]:
[代碼風格] :
[是否頭一次寫此類driver funcion的代碼] :
[潛臺詞] :
class Solution { public int numDistinctIslands(int[][] grid) { //corner cases if (grid == null || grid.length == 0 || grid[0].length == 0) return 0; //initialization: StringBuilder, hashset StringBuilder curShape; Set<String> set = new HashSet<String>(); //start to expand if grid[i][j] == 1 for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] == 1) { curShape = new StringBuilder(); expandIslands(grid, i, j, curShape, ""); //add to set after trimed set.add(curShape.toString().trim()); } } } //return keyset return set.size(); } public void expandIslands(int[][] grid, int x, int y, StringBuilder curShape, String directions) { //exit case if (grid[x][y] == 0 || x < 0 || x >= grid.length || y < 0 || y >= grid[0].length) return ; //set grid[x][y] = 0 grid[x][y] = 0; //append the cur directions curShape.append(directins); //expand in 4 directions expandIslands(grid, x - 1, y, curShape, "U"); expandIslands(grid, x + 1, y, curShape, "D"); expandIslands(grid, x, y + 1, curShape, "R"); expandIslands(grid, x, y - 1, curShape, "L"); //add a * if neccessary curShape.append(" "); } }