[Leetcode-200]Number of Islands 陆地的数量

来源:互联网 发布:淘宝x360手柄 编辑:程序博客网 时间:2024/05/01 03:55

本文概要

  • 本文概要
  • 分析
  • AC 代码

Leetcode200. 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:

11110110101100000000

Answer: 1

Example 2:

11000110000010000011

Answer: 3

分析

DFS方法:
选取陆地 然后上下左右四个方向遍历延展, 将周围与之相邻的所有陆地标记为水域。

能进行几次标记, 就说明有几块陆地。

AC 代码

这里写图片描述

class Solution {public:    void help(vector<vector<char> > &a, int x, int y){        if((x<0)|| (x>= a.size())|| (y<0) || (y>= a[x].size()) || (a[x][y] != '1')){ //如果没有越界 而且 已经是水域 则直接返回            return;        }          a[x][y] = '0';        help(a, x-1, y);//左        help(a, x+1, y);//右        help(a, x, y+1);//上        help(a, x, y-1);//下    }    int numIslands(vector<vector<char>>& grid) {        int answer = 0;        for(int i=0; i<grid.size(); i++){            for(int j=0; j< grid[i].size(); j++){                if(grid[i][j] == '1'){                    help(grid, i, j);                    answer++;                }            }        }        return answer;    }};
原创粉丝点击