zoukankan      html  css  js  c++  java
  • 【LeetCode & 剑指offer刷题】回溯法与暴力枚举法题6:Number of Islands

    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

    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:
    Input:
    11110
    11010
    11000
    00000
     
    Output: 1
    Example 2:
    Input:
    11000
    11000
    00100
    00011
     
    Output: 3

    C++
     
        这道求岛屿数量的题的本质是求矩阵中连续区域的个数,很容易想到需要用深度优先搜索DFS来解,我们需要建立一个visited数组用来记录某个位置是否被访问过,
        对于一个为‘1’且未被访问过的位置,我们递归进入其上下左右位置上为‘1’的数,将其visited对应值赋为true,继续进入其所有相连的邻位置,这样可以将这个连通区域所有的数找出来,并将其对应的visited中的值赋true,
        找完次区域后,我们将结果res自增1,然后我们在继续找下一个为‘1’且未被访问过的位置,以此类推直至遍历完整个原数组即可得到最终结果,代码如下:
     
    class Solution {
    public:
        int numIslands(vector<vector<char> > &grid)
        {
            if (grid.empty() || grid[0].empty()) return 0;
           
            int m = grid.size(), n = grid[0].size();
            int result = 0;
            vector<vector<bool> > visited(m, vector<bool>(n, false)); //创建访问矩阵
            for (int i = 0; i < m; i++) //遍历栅格中所有元素(因为每个点都有可能为某个岛屿的某点)
            {
                for (int j = 0; j < n; j++)
                {
                    if (grid[i][j] == '1' && !visited[i][j]) {
                        numIslandsDFS(grid, visited, i, j); //向相邻方向(上下左右)走当遇到越界,或者遇到0或者遇到访问过的1后,递归函数退出,所有递归分支退出后,该递归函数结束,找到一个岛屿
                        result++; //统计岛屿的个数
                    }
                }
            }
            return result;
        }
        void numIslandsDFS(vector<vector<char> > &grid, vector<vector<bool> > &visited, int x, int y) {
            if (x < 0 || x >= grid.size()) return;
            if (y < 0 || y >= grid[0].size()) return; //超出范围时退出
            if (grid[x][y] != '1' || visited[x][y]) return; //如果不为1或者访问过就退出
           
            visited[x][y] = true;
            numIslandsDFS(grid, visited, x - 1, y);
            numIslandsDFS(grid, visited, x + 1, y);
            numIslandsDFS(grid, visited, x, y - 1);
            numIslandsDFS(grid, visited, x, y + 1);
        }
    };
  • 相关阅读:
    50 系统调用的实现
    49 进程调度预备开发(下)
    48 进程调度预备开发(上)
    47 多进程并行执行(下)
    IIC总线
    46 多进程并行执行(上)
    45 内核中的中断处理(下)
    解决错误/usr/bin/ld: cannot find -lz
    rsync只传输隐藏文件
    Firewall命令
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10229466.html
Copyright © 2011-2022 走看看