ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

694. Number of Distinct Islands

2021-04-08 09:35:46  阅读:237  来源: 互联网

标签:Distinct island Number int length grid sb Islands dir


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 }

 

标签:Distinct,island,Number,int,length,grid,sb,Islands,dir
来源: https://www.cnblogs.com/beiyeqingteng/p/14630651.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有