zoukankan      html  css  js  c++  java
  • 200. Number of Islands (Graph)

    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(意思是,如果仅仅是斜角都为1,不是ajacent land). 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,表示找到了一个island,然后找它的连通图,把这个连通图里的1都设置标志。

    class Solution {
    public:
        int numIslands(vector<vector<char>>& grid) {
            int hight = grid.size();
            if(hight == 0) return 0;
            int width = grid[0].size();
            int ret = 0;
            
            for(int i = 0; i < hight; i++){
                for(int j = 0; j < width; j++){
                    if(grid[i][j]=='0') continue;
                    
                    //find a land, continue to find land at its side
                    ret++;
                    grid[i][j] = '0'; //set flag
                    dfs(grid, i+1, j);
                    dfs(grid, i, j+1);
                    dfs(grid, i-1, j);
                    dfs(grid, i, j-1);
                }
            }
            return ret;
        }
        
        void dfs(vector<vector<char>>& grid, int i, int j){
            int hight = grid.size();
            int width = grid[0].size();
            
            if(i>=hight || j>= width || i<0 || j<0) return;
            if(grid[i][j]=='0') return;
                
            //find a land, continue to find land at its side
            grid[i][j] = '0'; //set flag
            dfs(grid, i+1, j);
            dfs(grid, i, j+1);
            dfs(grid, i-1, j);
            dfs(grid, i, j-1);
        }
    };
  • 相关阅读:
    Appium 自动化测试配置wda的两种方式。
    brew install jenkins
    运算符,流程控制语句,单分支,双分支,多分支
    程序交互,数据类型,格式化输出
    编程语言介绍,变量和常量
    “Hello world! ”
    斐波那锲数列 冒泡排序
    AssetBundle
    animation 老动画
    animator 新动画
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/5051194.html
Copyright © 2011-2022 走看看