LeetCode-Number of Islands

LiBlog發表於2016-08-15

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.

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[]>();
20         pointList.add(start);        
21 
22         while (!pointList.isEmpty()){
23             int[] head = pointList.poll();
24             for (int i=0;i<4;i++){
25                 int[] next = new int[]{head[0]+moves[i][0],head[1]+moves[i][1]};            
26                 if (next[0]>=0 && next[0]<grid.length && next[1]>=0 && next[1]<grid[0].length && grid[next[0]][next[1]] == '1'){
27                     pointList.add(next);
28                     grid[next[0]][next[1]] = '2';
29                 }
30             }
31         }
32     }
33 }