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。

  • 相关阅读:
    MATLAB入门学习(一)
    4.21小练
    poj2312 Battle City 【暴力 或 优先队列+BFS 或 BFS】
    Mutual Training for Wannafly Union #2
    4.7-4.9补题+水题+高维前缀和
    CodeForces 91A Newspaper Headline
    codeforces 792C. Divide by Three
    3.26-3.31【cf补题+其他】
    poj3259 Wormholes【Bellman-Ford或 SPFA判断是否有负环 】
    二叉树基础练习
  • 原文地址:https://www.cnblogs.com/gonuts/p/4438594.html
Copyright © 2011-2022 走看看