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。

  • 相关阅读:
    C# 中的类型转换
    Structured Query Language 入门 oracle
    C# 模板代碼的總結
    .net 頁面通過C#控件綁定時間格式的方法
    醫務室系統報表中使用的一個使用遊標的自定義方法 sqlserver
    vi 编译器的退出
    和为s的数字
    两个链表的第一个公共节点
    某数字在排序数组中出现的次数
    二叉搜索树的第k个节点
  • 原文地址:https://www.cnblogs.com/gonuts/p/4438594.html
Copyright © 2011-2022 走看看