Problem
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.
class Solution { public int numDistinctIslands(int[][] grid) { if (grid == null || grid.length == 0) return 0; Setset = new HashSet<>(); for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] == 1) { StringBuilder sb = new StringBuilder(); dfs(grid, i, j, sb, "start:"); grid[i][j] = 0; System.out.println(sb.toString()); set.add(sb.toString()); } } } return set.size(); } private void dfs(int[][] grid, int i, int j, StringBuilder sb, String dir) { if (i < 0 || i == grid.length || j < 0 || j == grid[0].length || grid[i][j] == 0) return; sb.append(dir); grid[i][j] = 0; dfs(grid, i-1, j, sb, "d"); dfs(grid, i+1, j, sb, "u"); dfs(grid, i, j-1, sb, "l"); dfs(grid, i, j+1, sb, "r"); sb.append("#"); } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/72408.html
摘要:解题思路标零法对这个矩阵进行循环访问每一个点当这个点等于,岛屿数量,与其同时用算法访问周围的其他点,进行同样的操作且将访问过且等于的点标记为零。版本岛屿数量搜索右边搜索左边搜索下边搜索上边 Q: Number of Islands Given a 2d grid map of 1s (land) and 0s (water), count the number of islands. ...
摘要:两个循环遍历整个矩阵,出现则将其周围相邻的全部标记为,用子函数递归标记。注意里每次递归都要判断边界。写一个的,写熟练。 Number of Islands Problem Given a boolean/char 2D matrix, find the number of islands. 0 is represented as the sea, 1 is represented as...
摘要:题目要求提供一个二维数组表示一张地图,其中代表陆地,代表海洋。这里使用一个新的二维数组来表示对应地图上的元素属于哪个并查集。在合并的时候先进行判断,如果二者为已经相连的陆地,则无需合并,否则将新的二维数组上的元素指向所在的并查集。 题目要求 Given a 2d grid map of 1s (land) and 0s (water), count the number of isla...
摘要:同时我们每找到一个,就将其标为,这样就能把整个岛屿变成。我们只要记录对矩阵遍历时能进入多少次搜索,就代表有多少个岛屿。 Number of Islands 最新更新的思路,以及题II的解法请访问:https://yanjia.me/zh/2018/11/... Given a 2d grid map of 1s (land) and 0s (water), count the nu...
Problem In a given 2D binary array A, there are two islands. (An island is a 4-directionally connected group of 1s not connected to any other 1s.) Now, we may change 0s to 1s so as to connect the two...
阅读 2382·2021-09-22 15:41
阅读 1436·2021-08-19 10:54
阅读 1716·2019-08-23 15:11
阅读 3362·2019-08-23 10:23
阅读 1401·2019-08-22 16:28
阅读 782·2019-08-22 15:11
阅读 718·2019-08-22 14:53
阅读 689·2019-08-22 13:49