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

    本周学习了DFS,因此在LeetCode中挑选了一道关于DFS的题目作为巩固。

    题目:200. 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

    题解:

      这道题是经典的通过DFS求联通块的题目。由于grid中每一个点都有可能是成为发现的新island中的第一个点,于是在主函数(numIslands)中,需要对每一个陆地元素为起点进行DFS。在主函数中的每一次DFS结束之后,说明已经完成了一个岛屿的遍历,因此需要对岛屿总数计数器进行递增。

         对于DFS中的操作,一般而言对于图的DFS遍历,都通过一个visited二维数组来判断这个节点是否遍历过,但是这里由于题目的特性,可以通过将已经遍历过的陆地置0求得。也就是说,在每一次DFS中,将当前节点grid值置零,然后判断这个节点的上下左右邻域是否越界。如果不越界,并且是陆地,就继续DFS递归下去。

    class Solution {
    public:
        
        void dfs(vector<vector<char>>& grid, int y, int x)
        {
            int rows = grid.size();
            int cols = grid[0].size();
            if(x>=cols || x<0 || y<0 || y>=rows) return; 
            
            grid[y][x] = '0'; //说明已经遍历过了这个节点
            if(x-1>=0 && grid[y][x-1] == '1') dfs(grid,y,x-1);
            if(y-1>=0 && grid[y-1][x] == '1') dfs(grid,y-1,x);
            if(x+1 < cols && grid[y][x+1] =='1') dfs(grid,y,x+1);
            if(y+1 < rows && grid[y+1][x] =='1') dfs(grid,y+1,x);
        }
        
        int numIslands(vector<vector<char>>& grid) {
            if(grid.empty()) return 0;
            
            int totalIsland = 0;
            int rows = grid.size();
            int cols = grid[0].size();
    
            for(int i = 0 ; i < rows ; i ++)
            {
                for(int j = 0 ; j < cols; j ++)
                {
                    if(grid[i][j]=='1')
                    {
                       dfs(grid,i,j);  
                       //当每一次完成这样的遍历之后,就说明一个岛已经遍历完
                       totalIsland ++;
                    }
                }
            }
    
            return totalIsland;
        }
    
    };
  • 相关阅读:
    python3 driver chrome This version of ChromeDriver only supports Chrome version 89
    centos7 conda 安装 tensorflow
    python3 selenium Google浏览器 自动登录
    Fiddler Script
    深夜看了张一鸣的微博,让我越想越后怕(转载)
    OpenCV相关库
    .NET 面试题汇总(带答案)
    Java面试题
    定制化知识图谱 项目介绍
    关于《社会主义经济理论》若干问题的思考《九》
  • 原文地址:https://www.cnblogs.com/MT-ComputerVision/p/6579926.html
Copyright © 2011-2022 走看看