# LeetCode Number of Islands

Description:

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:

11110110101100000000

Example 2:

11000110000010000011

Solution:

import java.util.*;

public class Solution {
int m, n;
int dir[][] = new int[][] { { 1, 0 }, { 0, 1 }, { 0, -1 }, { -1, 0 } };

public int numIslands(char[][] grid) {
this.m = grid.length;
if (m == 0)
return 0;
this.n = grid[0].length;

int a, b, da, db;

int count = 0;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
if (grid[i][j] != '1')
continue;
grid[i][j] = '0';
count++;
while (!mList.isEmpty()) {
a = mList.poll();
b = nList.poll();

for (int k = 0; k < 4; k++) {
da = a + dir[k][0];
db = b + dir[k][1];
if (valid(grid, da, db)) {
grid[da][db] = '0';
}
}
}
}

return count;
}

boolean valid(char[][] grid, int a, int b) {
if (a < 0 || a >= m)
return false;
if (b < 0 || b >= n)
return false;
if (grid[a][b] == '1')
return true;
return false;
}

public static void main(String[] args) {
Solution s = new Solution();
System.out.println(5 & 6 & 7);
}
}

• 本文已收录于以下专栏：

## [LeetCode]200. Number of Islands

[LeetCode]200. Number of Islands题目描述思路BFS深搜，遍历，如果点为1，计数+1，并用深搜的方式将和他连通的为1的点均置0GFS留坑代码BFSclass Soluti...
• Lcharon
• 2017年03月07日 17:17
• 3035

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

## [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 surr...

## Leetcode-200. Number of Islands

• mcf171
• 2016年12月30日 21:11
• 136

## leetcode_Number of Islands_medium--dfs

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

## (LeetCode 200)Number of Islands(并查集、DFS)

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

## [LeetCode305]Number of Islands II

Hard..A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLan...

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

举报原因： 您举报文章：LeetCode Number of Islands 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)