题目:岛屿数量

使用的是深度优先搜素

主要思路:对输入的二维数组进行遍历,如果遇到一,则认为遇到了一个新的岛屿,然后对这个1周围上下左右四个元素进行搜索;如果周围元素仍然是1,就可以认为它与上一个区域位于同一个岛屿,并再次以当前这个一为起点,调用DFS函数递归搜索

DFS函数的终止条件是遇到零,因此每当遍历完成一个‘1’时,都要将其设置为‘0’,避免重复搜索导致栈溢出

numIslands()

 1class Solution
 2{
 3public:
 4    void DFS(vector<vector<char>>& grid, int x, int y)
 5    {
 6        for(int k = 0; k < 4; k++)
 7        {
 8            int next_x = x + dir[k][0];
 9            int next_y = y + dir[k][1];
10
11            if(next_x < 0 || next_x >= grid.size()) continue;
12            if(next_y < 0 || next_y >= grid[0].size()) continue;
13            if(grid[next_x][next_y] == '1')
14            {
15                grid[next_x][next_y] = '0';
16                DFS(grid, next_x, next_y);
17            }
18        }
19    }
20
21    int numIslands(vector<vector<char>>& grid)
22    {
23        int   m = grid.size();     // row
24        int   n = grid[0].size();  // column
25        int res = 0;
26
27        for(int i = 0; i < m; i++)
28        {
29            for(int j = 0; j < n; j++)
30            {
31                if(grid[i][j] == '1')
32                {
33                    res++;
34                    grid[i][j] = '0';
35                    DFS(grid, i, j);
36                }
37            }
38        }
39        return res;
40    }
41private :
42    int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1};
43};

来源:语雀原笔记