zoukankan      html  css  js  c++  java
  • 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

    思路:In this problem, we will use a algorithm called "Flood Fill".

    Here is a link about flood fill: http://www.geeksforgeeks.org/flood-fill-algorithm-implement-fill-paint/

    So, our idea is, when we found a '1', we increase count by 1 and mark all adjacent '1's as '2'. Then we keep searching next '1'.

    Code:

     1 public int numIslands(char[][] grid) {
     2         if (grid == null || grid.length == 0 || grid[0].length == 0) {
     3             return 0;
     4         }
     5         int count = 0;
     6         for (int i = 0; i < grid.length; i++) {
     7             for (int j = 0; j < grid[0].length; j++) {
     8                 if (grid[i][j] == '1') {
     9                     count++;
    10                     floodfill(i, j, grid);
    11                 }else{
    12                     continue;
    13                 }
    14             }
    15         }
    16         return count;
    17     }
    18     
    19     private static void floodfill(int x, int y, char[][] grid) {
    20         if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length) {
    21             return;
    22         }
    23         if (grid[x][y] != '1') {
    24             return;
    25         }
    26         grid[x][y] = '2';
    27         floodfill(x + 1, y, grid);
    28         floodfill(x - 1, y, grid);
    29         floodfill(x, y + 1, grid);
    30         floodfill(x, y - 1, grid);
    31     }

    这个算法很简单明了,记下就好。但代码还可以优化。现在308ms。

  • 相关阅读:
    uvm_misc——杂货铺(miscellaneous)
    23种设计模式及其应用场景
    Hadoop TextInputFormat源码分析
    java字符串替换函数高效实现
    hadoop HA 之 QJM
    中文分词词性对照表
    计算两个字符串编辑距离
    java 图片处理
    zookeeper数据迁移
    正则表达式
  • 原文地址:https://www.cnblogs.com/gonuts/p/4438594.html
Copyright © 2011-2022 走看看