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 ...
随机推荐
- Windows Phone 8.1 页面导航
1. Windows Phone 8.1 的应用框架 一个应用拥有 1 个 Window,一个 Window 包含 1 个 Frame,一个 Frame 包含 多个 Page. 获取 Frame 的方 ...
- present的时候是可以直接回到第一个viewcon的
最新:我并没有记错,是可以直接回到的 [self.presentingViewController.presentingViewController dismissModalViewControlle ...
- js switch表达式的例子
switch 这种表达式在很多语言中都有,比如java, C等待, 使用switch比使用if else 来得方便,来得清晰. 前言 switch 这种表达式在很多语言中都有,比如java, C等待 ...
- PHP加解密相关函数
openssl_public_encrypt() - Encrypts data with public keyopenssl_public_decrypt() - Decrypts data w ...
- C# 读取oracle 中文乱码的解决方案
用OracleDataAccess.dll访问oracle数据库,遇到中文乱码的情况. 解决方案如下: 1查看字符集编码, 在数据库服务器端 启动 sqlplus SQL->select use ...
- 灵光乍现,lua数据绑定
MVVM的核心就是数据驱动,数据驱动的核心就是数据绑定. 我一直在思考,如何使用lua做一个数据绑定的功能,仔细思考一下,数据绑定需要做到的功能很简单,就是当一个数据改变时,能主动回调一个或多个函数就 ...
- 【BZOJ 3171】 [Tjoi2013]循环格
Description 一个循环格就是一个矩阵,其中所有元素为箭头,指向相邻四个格子.每个元素有一个坐标(行,列),其中左上角元素坐标为(0,0).给定一个起始位置(r,c) ,你可以沿着箭头防线在格 ...
- 搭建Git Server
windows上如何搭建Git Server Git在版本控制方面,相比与SVN有更多的灵活性,对于开源的项目,我们可以托管到Github上面,非常方便,但是闭源的项目就会收取昂贵的费用.那么私有 ...
- Elasticsearch升级至1.x后API的变化-三
请支持原创:http://www.cnblogs.com/donlianli/p/3841762.html 1.索引格式 1.x之前的版本,被索引的文档type会同时出现在url和传输的数据格式中 ...
- [Jquery] js验证手机号
function checkIdPhone(id,idErr){ var reg0=/^(13[0-9]|15[012356789]|18[01235,idErr6789]|14[57]|17[0]) ...