# LeetCode-Number of Islands

Datetime:2016-08-23 01:20:31         Topic: LeetCode          Share        Original >>

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:

Example 2:

Credits:

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

Solution:

Just BFS.

``` 1 public class Solution {
2     int[][] moves = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};
3
4     public int numIslands(char[][] grid) {
5         if (grid.length==0 || grid[0].length==0) return 0;
6         int count = 0;
7
8         for (int i=0;i<grid.length;i++)
9             for (int j=0;j<grid[0].length;j++)
10                 if (grid[i][j] == '1'){
11                     count++;
12                     markOneIsland(grid,new int[]{i,j});
13                 }
14
15         return count;
16     }
17
18     public void markOneIsland(char[][] grid, int[] start){
19         Deque<int[]> pointList = new LinkedList<int[]>();
21
22         while (!pointList.isEmpty()){
24             for (int i=0;i<4;i++){
26                 if (next[0]>=0 && next[0]<grid.length && next[1]>=0 && next[1]<grid[0].length && grid[next[0]][next[1]] == '1'){