200. Number of Islands
题目:
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
链接: http://leetcode.com/problems/number-of-islands/
题解:
Find number of islands。无向图求connected components,用dfs + bfs就可以解决了。这里其实有dfs剪枝。空间复杂度主要是递归栈的大小。
Time Complexity - O(mn), Space Complexity - O(mn)。
public class Solution {
public int numIslands(char[][] grid) { //undirected graph find connected components
if(grid == null || grid.length == 0)
return 0;
int count = 0;
for(int i = 0; i < grid.length; i++)
for(int j = 0; j < grid[0].length; j++)
if(grid[i][j] == '1') { // if isIsland, do dfs
dfs(grid, i, j);
count++;
}
return count;
}
private void dfs(char[][] grid, int i, int j) {
if(i > grid.length - 1 || j > grid[0].length - 1 || i < 0 || j < 0)
return;
if(grid[i][j] != '1')
return;
grid[i][j] = '0';
dfs(grid, i - 1, j); // Start BFS
dfs(grid, i, j - 1);
dfs(grid, i + 1, j);
dfs(grid, i, j + 1);
}
}
题外话: 11/14/2015,终于200题了!好高兴,又一个里程碑。下午休息休息,明天继续开始201,有时间的话也要回头总结题目,题型,加深思维能力, 主要是分析能力和思考速度。希望下个月能够完成300题,然后早日开始第二遍。 第二遍打算刷题,精炼代码的同时学习Python和JavaScript,也要了解一下Golang(原因是The Go Programming Language是柯尼汉大神写的,要买)。第二遍结束后就可以练一些小公司了。之间还要做一些项目,学习多线程,设计模式,系统设计,OO设计等等, Cousera的Crytography课和算法1课也要跟着上,时间真的很难够用。 继续加油吧! 也要锻炼身体。
法国被恐怖分子袭击了,好可怜。现在自己工作的WTC也是恐怖分子的焦点之一,要注意安全。希望法国人民平安,希望其他国家努力惩戒恐怖分子。
二刷:
回头看看自己之前写的代码...BFS和DFS都搞不清楚 -____-!! 现在有进步了...
这道题可以用DFS, BFS和Union-Find来完成。BFS和Union-Find要把2D 转换为 1D来对待,否则的话还要另外建立private class Node。
Java:
DFS: 因为有剪枝,所以时间复杂度是O(mn)。 其实应该设立一个boolean[][] visited矩阵来保存访问过的节点,这样就不用更改原始数组了。否则我们每次dfs时要把当前节点置'0',避免重复计算。
Time Complexity - O(mn), Space Complexity - O(mn)。
public class Solution {
public int numIslands(char[][] grid) {
if (grid == null) return 0;
int count = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
countIslands(grid, i, j);
count++;
}
}
}
return count;
}
private void countIslands(char[][] grid, int i, int j) {
if (grid[i][j] != '1') return;
grid[i][j] = '0';
if (i - 1 >= 0) countIslands(grid, i - 1, j);
if (i + 1 <= grid.length - 1) countIslands(grid, i + 1, j);
if (j - 1 >= 0) countIslands(grid, i, j - 1);
if (j + 1 <= grid[0].length - 1) countIslands(grid, i, j + 1);
}
}
BFS, 写得烂速度慢
public class Solution {
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) return 0;
int rowNum = grid.length, colNum = grid[0].length;
boolean[][] visited = new boolean[rowNum][colNum];
Queue<int[]> q = new LinkedList<>();
int count = 0;
for (int i = 0; i < rowNum; i++) {
for (int j = 0; j < colNum; j++) {
if (!visited[i][j] && grid[i][j] == '1') {
q.offer(new int[] {i, j});
while (!q.isEmpty()) {
int[] location = q.poll();
int k = location[0], l = location[1];
if (visited[k][l]) continue;
visited[k][l] = true;
if (k - 1 >= 0 && grid[k - 1][l] == '1' && !visited[k - 1][l]) q.offer(new int[] {k - 1, l});
if (k + 1 <= rowNum - 1 && grid[k + 1][l] == '1' && !visited[k + 1][l]) q.offer(new int[] {k + 1, l});
if (l - 1 >= 0 && grid[k][l - 1] == '1' && !visited[k][l - 1]) q.offer(new int[] {k, l - 1});
if (l + 1 <= colNum - 1 && grid[k][l + 1] == '1' && !visited[k][l + 1]) q.offer(new int[] {k, l + 1});
}
count++;
}
}
}
return count;
}
}
BFS简化版, 速度还是慢。用Queue<int[]>的好处是我们不用每次都新建一个Node了。不过使用int[2]的空间开销和 Node(int x, int y)的开销都差不多。
- 在64位系统里, int[2] 是24 bytes + 4 * 2 bytes= 32 bytes
- Node {int x int y} 是16 bytes (object overhead) + 4 * 2 bytes = 24 bytes
- 比较一下还是新建Node比较划算。假如有Reference field的话那也是8 bytes.
public class Solution {
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) return 0;
int rowNum = grid.length, colNum = grid[0].length;
Queue<int[]> q = new LinkedList<>();
int count = 0;
for (int i = 0; i < rowNum; i++) {
for (int j = 0; j < colNum; j++) {
if (grid[i][j] == '1') {
q.offer(new int[] {i, j});
while (!q.isEmpty()) {
int[] location = q.poll();
int k = location[0], l = location[1];
if (grid[k][l] != '1') continue;
grid[k][l] = 0;
if (k - 1 >= 0) q.offer(new int[] {k - 1, l});
if (k + 1 <= rowNum - 1) q.offer(new int[] {k + 1, l});
if (l - 1 >= 0) q.offer(new int[] {k, l - 1});
if (l + 1 <= colNum - 1) q.offer(new int[] {k, l + 1});
}
count++;
}
}
}
return count;
}
}
使用Union-Find速度可能会更慢一些
四刷:
class Solution {
int[][] directions = new int[][] {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) return 0;
int count = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
dfs(grid, i, j);
count++;
}
}
}
return count;
}
private void dfs (char[][] grid, int i, int j) {
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] != '1') return;
grid[i][j] = '0';
for (int[] direction : directions)
dfs(grid, i + direction[0], j + direction[1]);
}
}
Reference:
https://leetcode.com/discuss/31014/java-undirected-graph-connected-components
https://leetcode.com/discuss/41053/java-dfs-and-bfs-solution
https://leetcode.com/discuss/79537/java-union-find-solution
200. Number of Islands的更多相关文章
- leetcode 200. Number of Islands 、694 Number of Distinct Islands 、695. Max Area of Island 、130. Surrounded Regions
两种方式处理已经访问过的节点:一种是用visited存储已经访问过的1:另一种是通过改变原始数值的值,比如将1改成-1,这样小于等于0的都会停止. Number of Islands 用了第一种方式, ...
- Leetcode 200. number of Islands
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surro ...
- Java for LeetCode 200 Number of Islands
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surro ...
- [LeetCode] 200. Number of Islands 解题思路
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surro ...
- (BFS/DFS) leetcode 200. Number of Islands
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surro ...
- 200. Number of Islands(DFS)
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surro ...
- leetcode题解 200. Number of Islands(其实就是一个深搜)
题目: Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is s ...
- [leetcode]200. Number of Islands岛屿个数
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surro ...
- 200. Number of Islands (Graph)
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surro ...
随机推荐
- CAD输出的局部平面坐标数据配准转换到WGS84坐标系
局部平面坐标 平移纠正到常用平面坐标系下的坐标 转换后的地理坐标 采用两 ...
- Bootstrap学习笔记(三) 网格系统
4-1实现原理 网格系统的实现原理非常简单,仅仅是通过定义容器大小,平分12份(也有平分成24份或32份,但12份是最常见的),再调整内外边距,最后结合媒体查询,就制作出了强大的响应式网格系统.Boo ...
- 暑假集训(4)第八弹——— 组合(hdu1524)
题意概括:你已经赢得两局,最后一局是N个棋子往后移动,最后一个无法移动的玩家失败. 题目分析:有向无环图sg值游戏,尼姆游戏的抽象表达.得到每个棋子的sg值之后,把他们异或起来,考察异或值是否为0. ...
- Call C# code from C++
Reference: https://support.microsoft.com/en-us/kb/828736 Calling C# .NET methods from unmanaged C/C+ ...
- CSMA-CA介绍
本文主要介绍通讯领域中CSMA相关机制,本文全部资料来自于网络. 网络通讯,必须依靠介质来传递数据,将数据调制到模拟信号上,再把此信号通过介质传递到远方.根据介质的不同,分为有线网络和无线网络.为 ...
- 视酷即时通讯系统应用源码 V1.0
视酷即时通讯系统(原创),成熟稳定,拥有和微信一样强大的功能不再是梦,节省几个月研发时间迅速融合进项目中: 1.首家支持聊天室群聊 2.支持和微信一样的语音聊天,可以显示时长.未读状态,自动轮播未读语 ...
- bower——库管理工具
bower了解: 随着网页功能的复杂化,各种网页效果的实现,现在单一的一个或两个库文件或许已经不能够满足我们的需要,但当有很多的库文件的时候,手动编辑已经不能胜任,对于引入的库文件而言,往往都是牵一发 ...
- 同时存在两个或多个homestead 虚拟box
开发中发现,不同版本的homestead 里面的环境各不相同,里面的node,npm等版本都不一致,如果需要添加 不同版本的homestead同时存在可以按照以下办法处理. tips: 提供可以离线下 ...
- C#实现网络传输数据加密
1. 分组密码 分组密码是将明文消息编码表示后数字序列划分成长为n的分组,各组分别在密钥的作用下进行变换输出等长的数字序列,即密文.一次加密一个数据组,加解密所使用的是同一密钥,故其通常也称为对称加密 ...
- Python字符串内建处理函数
#coding=utf-8 __author__ = 'Administrator' # 字符串处理函数 s1 = "study python string function , I lov ...