题目:

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)的开销都差不多。

  1. 在64位系统里, int[2] 是24 bytes + 4 * 2 bytes= 32 bytes
  2. Node {int x int y} 是16 bytes (object overhead) + 4 * 2 bytes = 24 bytes
  3. 比较一下还是新建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的更多相关文章

  1. 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 用了第一种方式, ...

  2. 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 ...

  3. 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 ...

  4. [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 ...

  5. (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 ...

  6. 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 ...

  7. 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 ...

  8. [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 ...

  9. 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 ...

随机推荐

  1. Windows7下安装搭建play框架

    作者:Sungeek 出处:http://www.cnblogs.com/Sungeek/ 欢迎转载,也请保留这段声明.谢谢! 1.首先官网下载play的解压包 https://playframewo ...

  2. 【原】从/dev/null重新打开标准输出

    今天遇到一个程序,使用了printf输出中间的信息,我也懒得去改.由于此进程被其他进程fork之后,dup2 了标识输入输出到了/dev/null,再通过execvp装载进来.于是,为了看到输出的信息 ...

  3. 仿《雷霆战机》飞行射击手游开发--GameObject

    转载请注明:http://www.cnblogs.com/thorqq/p/5646509.html 在上一篇中,我们介绍了各种游戏对象的功能及类的集成关系,现在我们来看看GameObject的源代码 ...

  4. wamp Server2.5 配置 自定义目录

    煎熬了两天终于找到了方法!!! 前提先改成中文 右键"W"图表-> Language -> chinese; 成功改为中文. 自定义目录步骤: 一.添加一个Alias ...

  5. javascript学习笔记(5

    1.string Array Date Math 内置对象的属性和方法? 答案: ①String 字符串 属性 :length  获取字符串长度 方法: indexOf()  从左到右检索子字符串在原 ...

  6. php curl抓取远程页面内容的代码

    使用php curl抓取远程页面内容的例子. 代码如下: <?php /** * php curl抓取远程网页内容 * edit by www.jbxue.com */ $curlPost = ...

  7. php连接ftp

    PHP连接ftp,发现一个很好用的类库phpseclib.英文原文 Connecting to SFTP with PHP If you need to connect to SFTP using P ...

  8. discuz X2.5自己写代码,获取当前登录的用户信息

    <? //这个只是获取当前用户账号以及积分的方法,同样你修改SQL语句可以实现discuz所有数据处理的功能 require '../source/class/class_core.php';/ ...

  9. KM3

    本科:读完一本书,知道book里讲的是什么,带有知识吸收: 硕士:读完一本书,知道book里的内容,而且还能发现相关的问题,带有知识的思考: 博士:读完一本书,知道book里的内容,而且还能发现相关的 ...

  10. .NET基础之迭代器

    使用foreach循环是有IEnumerator接口来实现的,IEnumerator即实现了迭代器,在foreach中如何迭代一个集合arrayList呢? 调用arrayLis.GetEnumber ...