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);
        }
    };
  • 相关阅读:
    redis——事务
    redis——队列
    linux安装mysql5.7
    转载:centos7yum默认为阿里云镜像
    redis——缓存穿透、缓存击穿、缓存雪崩
    redis——持久化
    redis——分布式锁
    并发编程实践
    Java并发包中线程同步器
    并发包中ScheduledThreadPoolExecutor
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/5051194.html
Copyright © 2011-2022 走看看