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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

本质是求矩阵中连续区域的个数, 可以用BFS, DFS, 或者 Union Find来解。

Java: BFS

class Coordinate {
int x, y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
} public class Solution {
public int numIslands(boolean[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
} int n = grid.length;
int m = grid[0].length;
int islands = 0; for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j]) {
markByBFS(grid, i, j);
islands++;
}
}
} return islands;
} private void markByBFS(boolean[][] grid, int x, int y) {
int[] directionX = {0, 1, -1, 0};
int[] directionY = {1, 0, 0, -1};
Queue<Coordinate> queue = new LinkedList<>();
queue.offer(new Coordinate(x, y));
grid[x][y] = false; while (!queue.isEmpty()) {
Coordinate coor = queue.poll();
for (int i = 0; i < 4; i++) {
Coordinate adj = new Coordinate(
coor.x + directionX[i],
coor.y + directionY[i]
);
if (!inBound(adj, grid)) {
continue;
}
if (grid[adj.x][adj.y]) {
grid[adj.x][adj.y] = false;
queue.offer(adj);
}
}
}
} private boolean inBound(Coordinate coor, boolean[][] grid) {
int n = grid.length;
int m = grid[0].length; return coor.x >= 0 && coor.x < n && coor.y >= 0 && coor.y < m;
}
}

Java: DFS

public class Solution {
private int m, n;
public void dfs(boolean[][] grid, int i, int j) {
if (i < 0 || i >= m || j < 0 || j >= n) return; if (grid[i][j]) {
grid[i][j] = false;
dfs(grid, i - 1, j);
dfs(grid, i + 1, j);
dfs(grid, i, j - 1);
dfs(grid, i, j + 1);
}
} public int numIslands(boolean[][] grid) {
m = grid.length;
if (m == 0) return 0;
n = grid[0].length;
if (n == 0) return 0; int ans = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (!grid[i][j]) continue;
ans++;
dfs(grid, i, j);
}
}
return ans;
}
}

Java: Union Find

class UnionFind {
private int[] father = null;
private int count; private int find(int x) {
if (father[x] == x) {
return x;
}
return father[x] = find(father[x]);
} public UnionFind(int n) {
// initialize your data structure here.
father = new int[n];
for (int i = 0; i < n; ++i) {
father[i] = i;
}
} public void connect(int a, int b) {
int root_a = find(a);
int root_b = find(b);
if (root_a != root_b) {
father[root_a] = root_b;
count --;
}
} public int query() {
return count;
} public void set_count(int total) {
count = total;
}
} public class Solution {
public int numIslands(boolean[][] grid) {
int count = 0;
int n = grid.length;
if (n == 0)
return 0;
int m = grid[0].length;
if (m == 0)
return 0;
UnionFind union_find = new UnionFind(n * m); int total = 0;
for(int i = 0;i < grid.length; ++i)
for(int j = 0;j < grid[0].length; ++j)
if (grid[i][j])
total ++; union_find.set_count(total);
for(int i = 0;i < grid.length; ++i)
for(int j = 0;j < grid[0].length; ++j)
if (grid[i][j]) {
if (i > 0 && grid[i - 1][j]) {
union_find.connect(i * m + j, (i - 1) * m + j);
}
if (i < n - 1 && grid[i + 1][j]) {
union_find.connect(i * m + j, (i + 1) * m + j);
}
if (j > 0 && grid[i][j - 1]) {
union_find.connect(i * m + j, i * m + j - 1);
}
if (j < m - 1 && grid[i][j + 1]) {
union_find.connect(i * m + j, i * m + j + 1);
}
}
return union_find.query();
}
}

Python: BFS

class Solution:
def numIslands(self, grid):
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
visit = [[False for i in range(n)]for j in range(m)]
def check(x, y):
if x >= 0 and x < m and y >= 0 and y < n and grid[x][y] and visit[x][y] == False:
return True
def bfs(x,y):
nbrow = [1, 0, -1, 0]
nbcol = [0, 1, 0, -1]
q =[(x,y)]
while len(q) > 0:
x = q[0][0]
y = q[0][1]
q.pop(0)
for k in range(4):
newx = x + nbrow[k]
newy = y + nbcol[k]
if check(newx, newy):
visit[newx][newy] = True
q.append((newx,newy)) count = 0
for row in range(m):
for col in range(n):
if check(row,col):
visit[row][col] = True
bfs(row,col)
count+=1
return count

Python: DFS

class Solution:
def numIslands(self, grid):
if not grid:
return 0 row = len(grid)
col = len(grid[0])
count = 0
for i in xrange(row):
for j in xrange(col):
if grid[i][j] == '1':
self.dfs(grid, row, col, i, j)
count += 1
return count def dfs(self, grid, row, col, x, y):
if grid[x][y] == '0':
return
grid[x][y] = '0' if x != 0:
self.dfs(grid, row, col, x - 1, y)
if x != row - 1:
self.dfs(grid, row, col, x + 1, y)
if y != 0:
self.dfs(grid, row, col, x, y - 1)
if y != col - 1:
self.dfs(grid, row, col, x, y + 1)

Python: DFS

class Solution(object):
def findIslands(self, M):
if not M:
return 0 res = 0
for i in xrange(len(M)):
for j in xrange(len(M[0])):
if M[i][j] == 1:
res += 1
self.dfs(M, i, j) return res def dfs(self, m, x, y):
if m[x][y] == 1:
m[x][y] = 0
if x > 0:
self.dfs(m, x - 1, y)
if y > 0:
self.dfs(m, x, y - 1)
if x < len(m) - 1:
self.dfs(m, x + 1, y)
if y < len(m[0]) - 1:
self.dfs(m, x, y + 1)  

Python: BFS

class Solution(object):
def findIslands(self, M):
if not M:
return 0 res = 0
for i in xrange(len(M)):
for j in xrange(len(M[0])):
if M[i][j] == 1:
res += 1
print res
self.bfs(M, i, j) return res def checkPoint(self, m, x, y):
if x < 0 or y < 0 or x > len(m) - 1 or y > len(m[0]) - 1 or m[x][y] == 0:
return False return True def bfs(self, m, x, y):
x_row = [0, 0, -1, 1]
y_col = [-1, 1, 0, 0]
queue = [(x, y)]
while len(queue) > 0:
point = queue.pop(0)
row = point[0]
col = point[1]
if m[row][col] == 1:
m[row][col] = 0
for i in xrange(4):
if self.checkPoint(m, row + x_row[i], col + y_col[i]):
queue.append((row + x_row[i], col + y_col[i])) 

Python: DFS

class Solution:
def numIslands(self, grid):
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
visit = [[False for i in range(n)]for j in range(m)]
def check(x, y):
if x >= 0 and x < m and y >= 0 and y < n and grid[x][y] and visit[x][y] == False:
return True
def dfs(x, y):
nbrow = [1,0,-1,0]
nbcol = [0,1,0,-1]
for k in range(4):
newx = x + nbrow[k]
newy = y + nbcol[k]
if check(newx, newy):
visit[newx][newy] = True
dfs(newx,newy)
count = 0
for row in range(m):
for col in range(n):
if check(row, col):
visit[row][col] = True
dfs(row, col)
count+=1
return count

  

类似题目:

[LeetCode] 305. Number of Islands II 岛屿的数量 II

[LeetCode] 547. Friend Circles 朋友圈

[LeetCode] 79. Word Search 单词搜索

All LeetCode Questions List 题目汇总

  

[LeetCode] 200. Number of Islands 岛屿的数量的更多相关文章

  1. LeetCode 200. Number of Islands 岛屿数量(C++/Java)

    题目: Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is s ...

  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. [leetcode]200. Number of Islands岛屿数量

    dfs的第一题 被边界和0包围的1才是岛屿,问题就是分理出连续的1 思路是遍历数组数岛屿,dfs四个方向,遇到1后把周围连续的1置零,代表一个岛屿. /* 思路是:遍历二维数组,遇到1就把周围连续的1 ...

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

  5. 【LeetCode】200. Number of Islands 岛屿数量

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 题目地址:https://le ...

  6. [LeetCode] 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 ...

  7. [LeetCode] 0200. Number of Islands 岛屿的个数

    题目 Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is su ...

  8. [LintCode] Number of Islands 岛屿的数量

    Given a boolean 2D matrix, find the number of islands. Notice 0 is represented as the sea, 1 is repr ...

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

随机推荐

  1. C#模拟鼠标、键盘操作

    C语言 在程序中打开网页,模拟鼠标点击.键盘输入 一.简述         记--使用C语言 打开指定网页,并模拟鼠标点击.键盘输入.实现半自动填写账号密码,并登录网站(当然现在的大部分网站都有验证码 ...

  2. 1220 Vue与Django前后端的结合

    目录 vue的安装 Vue前端的设置 页面的分布 后台数据的替换 css样式 Django的配置 国际化配置 axios插件安装 CORS跨域问题(同源策略) 处理跨域问题: cors插件 axios ...

  3. DNS隧道

    自己使用的dns隧道通过两种方法,一种是通过dnscat2工具,另一种通过cs上的beacon来进行通信. 第一种方法:dnscat2: 参考文章:https://xz.aliyun.com/t/22 ...

  4. Guava com.google.common.base.Stopwatch Spark程序在yarn中 MethodNotFound

    今天在公司提交一个Spark 读取hive中的数据,写入JanusGraph 的app,自己本地调试没有问题,放入环境中提交到yarn 中时,发现app 跑不起. yarn 中日志,也比较明显,app ...

  5. BZOJ 4103: [Thu Summer Camp 2015]异或运算 可持久化trie

    开始想了一个二分+可持久化trie验证,比正解多一个 log 仔细思考,你发现你可以直接按位枚举,然后在可持久化 trie 上二分就好了. code: #include <bits/stdc++ ...

  6. 2019.12.09 Random 随机数类

    //导包import java.util.Random;class Demo02 { public static void main(String[] args) { //创建Random对象 Ran ...

  7. WinDbg常用命令系列---!teb

    !teb 简介 !teb扩展显示线程环境块(teb)中信息的格式化视图. 使用形式 !teb [TEB-Address] 参数 TEB-Address 要检查其TEB的线程的十六进制地址.(这不是从线 ...

  8. WinDbg常用命令系列---异常相关操作

    .exr (Display Exception Record) .exr命令显示异常记录的内容. .exr Address .exr -1 参数: Address指定异常记录的地址.如果指定-1作为地 ...

  9. 事务控制语言(TCL)

    一个或一组sql语句组成一个执行单元,这个执行单元要么全部执行,要么全部不执行.如:转账. 原子性(Atomicity):一个事务要么都执行,要么都回滚(不可再分割) 一致性(Consistency) ...

  10. 怎么在浏览器设置cookie

    document.cookie="jwt=xxxxxx" 遇到了一个bug 开了代理没有办法做图片上传