ITPub博客

首页 > > > [LeetCode] Number of Islands

[LeetCode] Number of Islands

作者:Ruiyuan Li 时间:2015-04-09 00:00:00 0 删除 编辑

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

解题思路:

以前我做过这个题目,现在竟然全忘了,折腾了好久,看来每天都要保持锻炼啊。其实这道题思路挺简单的啊,就是递归标记而已。比如,若当前元素为‘1’,就递归将其左右上下为1的元素全部标记为‘0’,计数加1。(之前做的是积水,还包括对角处)。下面是代码;

class Solution {
public:
    int numIslands(vector> &grid) {
        int m = grid.size();
        if(m==0){
            return 0;
        }
        int n = grid[0].size();
        if(n==0){
            return 0;
        }
        
        int result = 0;
        for(int i=0; i> &grid, int m, int n, int i, int j){
        if(i<0||j<0 || i>=m||j>=n||grid[i][j]=='0'){
            return;
        }
        grid[i][j]='0';
        markRead(grid, m, n, i+1, j);
        markRead(grid, m, n, i, j+1);
        markRead(grid, m, n, i-1, j);
        markRead(grid, m, n, i, j-1);
    }
};


转载请注明: » [LeetCode] Number of Islands
<!-- -->

原文作者:;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4824