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
solution:
DFS + pruning
found 1 then search its up, left, down, right. Meanwhile change value to 2, pruning.
public int numIslands(char[][] grid) { int res = 0; int row = grid.length; if(row <=0) return 0; int col = grid[0].length; for(int i=0;i<row;i++){ for(int j=0;j<col;j++){ if(grid[i][j] == '1'){ res++; populateAdj(grid, i, j); } } } return res; } public void populateAdj(char[][] grid, int x, int y){ if(x>= grid.length || y>=grid[0].length || x<0 || y<0) return; if(grid[x][y] == '1') { grid[x][y] = '2'; populateAdj(grid, x-1, y); populateAdj(grid, x+1, y); populateAdj(grid, x, y-1); populateAdj(grid, x, y+1); } }