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
public class Solution { public int numIslands( char [][] grid) { int res = 0 ; int rows = grid.length; if (rows== 0 ) return res; int cols = grid[ 0 ].length; if (cols== 0 ) return res; int [] xdir = new int []{ 1 ,- 1 , 0 , 0 }; int [] ydir = new int []{ 0 , 0 , 1 ,- 1 }; ArrayList<Integer> queue_x = new ArrayList<Integer>(); ArrayList<Integer> queue_y = new ArrayList<Integer>(); for ( int i= 0 ;i<rows;i++){ for ( int j= 0 ;j<cols;j++){ if (grid[i][j]== '1' ){ res++; queue_x.add(i);queue_y.add(j); int low = 0 ; int high = 1 ; while (low<high){ for ( int k= 0 ;k< 4 ;k++){ int x = queue_x.get(low)+xdir[k]; int y = queue_y.get(low)+ydir[k]; if (x>= 0 &&x<rows&&y>= 0 &&y<cols){ if (grid[x][y]== '1' ){ grid[x][y]='0' ; queue_x.add(x); queue_y.add(y); high++; } } } low++; } queue_x.clear();queue_y.clear(); } } } return res; } }
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/46574435