首页 > 其他 > 详细

694. Number of Distinct Islands

时间:2021-04-08 10:14:18      阅读:14      评论:0      收藏:0      [点我收藏+]

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.

 1 class Solution {
 2     int[][] dirs = new int[][] { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };
 3     public int numDistinctIslands(int[][] grid) {
 4         Set<String> set = new HashSet<>();
 5         int res = 0;
 6 
 7         for (int i = 0; i < grid.length; i++) {
 8             for (int j = 0; j < grid[0].length; j++) {
 9                 if (grid[i][j] == 1) {
10                     StringBuilder sb = new StringBuilder();
11                     helper(grid, i, j, 0, 0, sb);
12                     String s = sb.toString();
13                     if (!set.contains(s)) {
14                         res++;
15                         set.add(s);
16                     }
17                 }
18             }
19         }
20         return res;
21     }
22 
23     public void helper(int[][] grid, int i, int j, int xpos, int ypos, StringBuilder sb) {
24         grid[i][j] = 0;
25         sb.append(xpos + "" + ypos);
26         for (int[] dir : dirs) {
27             int x = i + dir[0];
28             int y = j + dir[1];
29             if (x < 0 || y < 0 || x >= grid.length || y >= grid[0].length || grid[x][y] == 0)
30                 continue;
31             helper(grid, x, y, xpos + dir[0], ypos + dir[1], sb);
32         }
33     }
34 }

 

694. Number of Distinct Islands

原文:https://www.cnblogs.com/beiyeqingteng/p/14630651.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!