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

不同岛屿的数量。

思路还是跟200题差不多,也是dfs做,但是这里需要注意的是如何判断岛屿是不是重复的。我这里给出discussion最高票答案的思路。这其实是一个把信息序列化的思路,序列化的思想类似297题。既然是判断是否有重复的路径,那么应该是会利用到哈希来判断是否重复。但是如何将路径放入哈希呢,只能是序列化。这里hashset存的是一个岛屿被DFS过的路径。举个例子,当一开始在矩阵里面扫描的时候,遇到一个1,就开始做DFS递归遍历去他的四个方向再找1。此时可以将一开始找到的1 append到一个StringBuilder里面并且用“o”标记它为(目前这个岛的)原点original。DFS往四个方向遍历的时候,同时也往StringBuilder里面标记各自的方向。在不考虑翻转和旋转的情况下,可以有效查找出不同的岛屿。回溯的时候记得多加一个字母表示回溯,否则类似这样的case是判断不出来的。

/** WARNING: DO NOT FORGET to add path for backtracking, otherwise, we may have same result when we count two 
     * distinct islands in some cases
     * 
     * eg:              1 1 1   and    1 1 0
     *                  0 1 0          0 1 1
     * with b:          rdbr           rdr
     * without b:       rdr            rdr
     * */

时间O(mn)

空间O(n)

Java实现

 1 class Solution {
 2     public int numDistinctIslands(int[][] grid) {
 3         Set<String> set = new HashSet<>();
 4         for (int i = 0; i < grid.length; i++) {
 5             for (int j = 0; j < grid[0].length; j++) {
 6                 if (grid[i][j] != 0) {
 7                     StringBuilder sb = new StringBuilder();
 8                     dfs(grid, i, j, sb, "o");
 9                     grid[i][j] = 0;
10                     set.add(sb.toString());
11                 }
12             }
13         }
14         return set.size();
15     }
16 
17     private void dfs(int[][] grid, int i, int j, StringBuilder sb, String dir) {
18         if (i < 0 || i == grid.length || j < 0 || j == grid[0].length || grid[i][j] == 0) {
19             return;
20         }
21         sb.append(dir);
22         grid[i][j] = 0;
23         dfs(grid, i - 1, j, sb, "u");
24         dfs(grid, i + 1, j, sb, "d");
25         dfs(grid, i, j - 1, sb, "l");
26         dfs(grid, i, j + 1, sb, "r");
27         // backtracking
28         sb.append("b");
29     }
30 }

flood fill题型总结

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/13099151.html