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 };
  • 相关阅读:
    http请求消息体和响应消息体
    整型常量
    C语言中字符串后面的'\0'
    String类
    二进制转成十六进制
    http消息头
    NULL和NUL
    拷贝构造函数和赋值表达式
    awk中的FS
    之前给女性网增加的一个滚动展示
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/5016641.html
Copyright © 2011-2022 走看看