[关闭]
@w1024020103 2017-07-10T12:54:24.000000Z 字数 1508 阅读 489

Number of Islands

LintCode LeetCode


image_1bklc3f4q1ihkeo92rv1emfa499.png-84.2kB
image_1bklc3ujb1qse13e42bk1rmo1uemm.png-24.8kB

这道题是BFS in matrix这一类问题,用到了Flood fill的方法。所有标记为1的点为岛屿,岛屿于上下左右的岛屿相通。
我们用两个for循环遍历整个矩阵,找到是岛屿的点,对其进行markByBFS,也就是对它周围上下左右的点进行检测标记。同时岛屿数加一,最后统计进行了markByBFS的次数,也就得到岛屿数目。

BFS部分跟在graph上基本一样,区别在于检测某个岛屿它上下左右的方块时,由于没有neighbors这个属性,需要通过坐标变换数组进行操作。坐标变换数组不唯一,只需要满足能遍历上下左右四个点就可以。在这个过程中,用一个inBound方法来限制我们遍历的范围不会越界。

自己画一下queue的offer和poll就很好理解Flood fill在这道题的运用。当我们发现第一个1时,立马将其标记为0,加入队列;当我们poll出刚才找到的那个点时,我们在它的上下左右找也是1的点,找到之后也标记为0,并加入队列。这种将原来是1的点Mark为0,并且像灌水一样将连着的都是1的点都mark为0的过程就是灌水法,很具体形象。

  1. class Coordinate{
  2. public int x;
  3. public int y;
  4. public Coordinate(int x, int y){
  5. this.x = x;
  6. this.y = y;
  7. }
  8. }
  9. public class Solution {
  10. /**
  11. * @param grid a boolean 2D matrix
  12. * @return an integer
  13. */
  14. public int numIslands(boolean[][] grid) {
  15. // Write your code here
  16. if (grid == null || grid.length == 0 || grid[0].length == 0){
  17. return 0;
  18. }
  19. int m = grid.length;
  20. int n = grid[0].length;
  21. int numOfIslands = 0;
  22. for (int i = 0; i < m; i ++){
  23. for (int j = 0 ; j < n; j++){
  24. if (grid[i][j] == true){
  25. markByBFS(grid,i, j);
  26. numOfIslands += 1;
  27. }
  28. }
  29. }
  30. return numOfIslands;
  31. }
  32. private void markByBFS(boolean[][] grid,int x, int y){
  33. int [] deltaX = {1,0,0,-1};
  34. int [] deltaY = {0,1,-1,0};
  35. Queue<Coordinate> queue = new LinkedList<Coordinate>();
  36. grid[x][y] = false;
  37. queue.offer(new Coordinate(x,y));
  38. while (!queue.isEmpty()){
  39. Coordinate coor = queue.poll();
  40. for (int i = 0; i < 4; i ++){
  41. Coordinate adj = new Coordinate(coor.x + deltaX[i], coor.y + deltaY[i]);
  42. if (!inBound(grid,adj.x,adj.y)){
  43. continue;
  44. }
  45. if (grid[adj.x][adj.y] == true){
  46. grid[adj.x][adj.y] = false;
  47. queue.offer(adj);
  48. }
  49. }
  50. }
  51. }
  52. private boolean inBound(boolean[][] grid, int x, int y){
  53. if ( x >= 0 && x < grid.length && y >= 0 && y < grid[0].length){
  54. return true;
  55. }
  56. return false;
  57. }
  58. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注