Leetcode: 200. Number of Islands (week4 --- medium)

题目

示例

分析

题解

总结


题目

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.

示例

分析

题目中的land可以是由很多个1所构成的,但是要求是这一块所有的1所构成的整体周围的其他元素均为0,也就是上下左右(视边界为0)。而题目要求正是找出这些“大陆”的个数。

题解

这一道题是BFS的题目,所以首先是考虑BFS的算法实现。而我们可以考虑在进行每个节点的遍历的时候,首先判断当前的节点是否为1,如果是1,则计数器加一,也就是对应的最后的返回值,然后判断其对应的四个方位的元素是否为1,然后跟上面的方式一样,将其位置的元素重置为0,但是计数器并不加一。因为当前属于同一个区域。只有发现第一个为1的时候才会进行加一操作。

而置为零则是为了防止重复计算陆地的数目,同时也是为了好区分。

所以实现的代码如下:

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        result = 0;
        int m = grid.size();    //row
        if( m == 0) return 0;
        int n = grid[0].size(); //col
        int array[m][n] = {0};
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == '1') {
                    result++;
                    dfs(grid, i, j);
                }  
            }
        } 
        return result;
    }
    void dfs(vector<vector<char>> &grid, int i, int j){
        grid[i][j] = '0';
        if(i > 0 && grid[i-1][j] == '1'){
            dfs(grid, i-1, j);
        }
        if(i < grid.size()-1 && grid[i+1][j] == '1'){
            dfs(grid, i+1, j);
        }
        if(j > 0 && grid[i][j-1] == '1'){
            dfs(grid, i, j-1);
        }
        if(j < grid[0].size()-1 && grid[i][j+1] == '1'){
            dfs(grid, i, j+1);
        }
    }
private:
    int result;
};

总结

  1. 根据老师上课讲的题目:主要存在以下几种题型
    1. 找出最小环
    2. 找出两点之间的最小路径以及路径的数目
    3. 对树的父子节点的公式更新规则
    4. 可以转化为强联通算法的体型
    5. 将题目的多种可选择操作作为分支的准则,从而能够转化为DFS或者NFS
    6. ...
  2. 觉得这一些算法要多去理解,以及去解解题才能够熟悉这些算法的应用。

猜你喜欢

转载自blog.csdn.net/qq_36347365/article/details/82901359
今日推荐