博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
694. Number of Distinct Islands - Medium
阅读量:7100 次
发布时间:2019-06-28

本文共 2110 字,大约阅读时间需要 7 分钟。

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:

11000110000001100011

Given the above grid map, return 1.

 

Example 2:

11011100000000111011

Given the above grid map, return 3.

Notice that:

111

and

111

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.

 

hashtable + dfs

在dfs找完整islands时,用StringBuilder存island增长的path,来表示其形状(从遍历到的第一个为1的点开始,每一个点向上/下/左/右走)

比如说 11 的形状是00 10 01,  1 的的形状是00 10 1-1

          1          11

每找到一个就存进set,防止重复。最后返回set的大小。

可以不用visited数组,直接将访问过的1赋值为0即可

时间:O(M*N),空间:O(M*N)

class Solution {    int[][] dirs = new int[][] {
{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; public int numDistinctIslands(int[][] grid) { if(grid == null || grid.length == 0) return 0; int m = grid.length, n = grid[0].length; Set
set = new HashSet<>(); for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(grid[i][j] == 1) { StringBuilder sb = new StringBuilder(); dfs(grid, i, j, 0, 0, sb); if(!set.contains(sb.toString())) set.add(sb.toString()); } } } return set.size(); } public void dfs(int[][] grid, int i, int j, int xpos, int ypos, StringBuilder sb) { grid[i][j] = 0; sb.append(xpos + "" + ypos); for(int[] dir : dirs) { int x = i + dir[0], y = j + dir[1]; if(x < 0 || x > grid.length - 1 || y < 0 || y > grid[0].length - 1 || grid[x][y] == 0) continue; dfs(grid, x, y, xpos + dir[0], ypos + dir[1], sb); } }}

 

转载于:https://www.cnblogs.com/fatttcat/p/10040079.html

你可能感兴趣的文章
vue在低版本的iOS下出现白屏现象解决方案
查看>>
vim从入门到弃坑:基础指令的归类
查看>>
[译] 苹果公司如何修复 3D Touch
查看>>
Linux下Git服务器架设
查看>>
如烟花般绚丽的区块链平台,剥下代币狼皮后如何生存?
查看>>
App爬虫神器mitmproxy和mitmdump的使用
查看>>
再说swift namespace
查看>>
初学 Android 架构组件之 ViewModel
查看>>
iOS AOP 框架 - Aspects 源码解读
查看>>
获取iOS客户端屏幕最上面的视图控制器
查看>>
iOS RunLoop分析
查看>>
canvas系列教程08-canvas各种坑
查看>>
单线程的js是如何工作的
查看>>
localStorage
查看>>
循环中的异步&&循环中的闭包
查看>>
外墙清洗机器人现身多幢大楼,清洗前后泾渭分明!
查看>>
算法与数据结构之枚举算法
查看>>
为什么Python发展这么快,有哪些优势?
查看>>
sublime-text3 安装 emmet 插件
查看>>
Promise 的then 里发生了什么
查看>>