zoukankan      html  css  js  c++  java
  • LeetCode-Number of Islands

    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 }
  • 相关阅读:
    S1 商品信息管理系统
    用例图
    mvc使用mongodb时objectId序列化与反序列化
    windows下检測文件改变
    【Android 开发实例】时间管理APP开发之数据库设计
    设计模式 之 原型
    ANT安装及配置
    Java环境变量设置
    Win7安装软件,界面上中文显示乱码的解决方案
    Some perl tips
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5772488.html
Copyright © 2011-2022 走看看