1. 程式人生 > >[leetcode]694. Number of Distinct Islands你究竟有幾個異小島?

[leetcode]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.

 

題目

此題是[leetcode]200. Number of Islands島嶼個數小島題的變種

要數出不同小島的個數,題意定義了不同小島: 互相不能通過非反射、旋轉而轉化

 

思路

- In 2D array, once we find 1st '1',  we find an island.  Meanwhile, we set a 'draw_begin' , ready to draw such island's shape

- DFS to loop through 4 different directions,  checking whether another '1' is connected with.  Meanwhile, we use u, d, l, r to draw island's shape.

- Once finish DFS, we set a 'draw_end',  indicating such island's drawing is done

- Why we use 'draw_begin' and  'draw_end' to set a bound ? 

-  要去handle 類似以下這種情況

11     and     1   
1            1 1

- Visited spots won't be visited again because they are updated to '0'

 

程式碼

 1 class Solution {
 2    public int numDistinctIslands(int[][] grid) {
 3         //put different drawing shape represented by string to hashset
 4         Set<String> set = new HashSet<>();
 5         for(int i = 0; i < grid.length; i++) { 
 6             for(int j = 0; j < grid[i].length; j++) {
 7                 if(grid[i][j] != 0) {
 8                     StringBuilder sb = new StringBuilder();
 9                     dfs(grid, i, j, sb, "draw_begin"); // set a bound
10                     set.add(sb.toString());
11                 }
12             }
13         }
14        // how many diffent shapes represented by string in hashset  
15         return set.size();
16     }
17     private void dfs(int[][] grid, int i, int j, StringBuilder sb, String dir) {
18         // out of bound or not an island 
19         if(i < 0 || i == grid.length || j < 0 || j == grid[i].length 
20            || grid[i][j] == 0) return;
21         
22         sb.append(dir);
23         grid[i][j] = 0;// mark a visted spot 
24         dfs(grid, i-1, j, sb, "u");// up
25         dfs(grid, i+1, j, sb, "d");// down 
26         dfs(grid, i, j-1, sb, "l");// left
27         dfs(grid, i, j+1, sb, "r");// right
28         sb.append("draw_end"); // set a bound 
29     }
30 }