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

    计算孤岛的数量,注意上下左右为0就是孤岛,孤岛可以很大,grid范围以外的都算是water。代码如下所示:

     1 class Solution {
     2 public:
     3     int numIslands(vector<vector<char>>& grid) {
     4         int count = 0;
     5         if(!grid.size() || !grid[0].size())
     6             return count;
     7           int row = grid.size();
     8           int col = grid[0].size();
     9           for(int i = 0; i < row; ++i){
    10               for(int j = 0; j < col; ++j){
    11                   if(grid[i][j] == '1'){
    12                       dfs(grid, i, j);
    13                       count++;
    14                   }
    15 
    16               }
    17           }
    18           return count;
    19     }
    20 
    21     void dfs(vector<vector<char>> & grid, int x, int y)
    22     {
    23         if(grid[x][y] == '1')
    24             grid[x][y] = 'X';
    25         else 
    26             return;
    27         dfs(grid, x+1, y);
    28         dfs(grid, x-1, y);
    29         dfs(grid, x, y+1);
    30         dfs(grid, x, y0);
    31     }
    32 };
  • 相关阅读:
    条件编译
    宏定义
    联合体,枚举类型
    结构体的概念
    C#程序报找不到时区错误
    C# ArrayList和List的区别
    C# 无法将类型为“__DynamicallyInvokableAttribute”的对象强制转换为类型...
    C# readonly与const区别
    C#特性
    Linux vsftpd 安装配置使用
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/5016641.html
Copyright © 2011-2022 走看看