leetcode 200. Number of Islands 十分典型的DFS深度优先遍历

雨点打透心脏的1/2处 2022-06-08 08:24 257阅读 0赞

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

这道题就是寻找连接在一起的1的数量,也就是岛屿的数量,这就是一个简单的DFS深度优先遍历应用,和这一道题leetcode 130. Surrounded Regions DFS + 矩阵遍历 ,基本一致,值得学习。

这是一个十分典型的DFS深度优先遍历的样例,值得学习!

代码如下:

  1. public class Solution
  2. {
  3. public int numIslands(char[][] grid)
  4. {
  5. if (grid == null || grid.length == 0 || grid[0].length == 0)
  6. return 0;
  7. int count = 0;
  8. for (int i = 0; i < grid.length; i++)
  9. {
  10. for (int j = 0; j < grid[0].length; j++)
  11. {
  12. if (grid[i][j] == '1')
  13. {
  14. count++;
  15. dfsSearch(grid, i, j);
  16. }
  17. }
  18. }
  19. return count++;
  20. }
  21. // 每遇到'1'后, 开始向四个方向 递归搜索. 搜到后变为'0',
  22. // 因为相邻的属于一个island. 然后开始继续找下一个'1'.
  23. private void dfsSearch(char[][] grid, int i, int j)
  24. {
  25. if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length
  26. || grid[i][j] != '1')
  27. return;
  28. // 也可以才用一个visited数组,标记遍历过的岛屿
  29. grid[i][j] = '0';
  30. dfsSearch(grid, i + 1, j);
  31. dfsSearch(grid, i - 1, j);
  32. dfsSearch(grid, i, j + 1);
  33. dfsSearch(grid, i, j - 1);
  34. }
  35. }

下面是C++的做法,就是一个很简单的DFS深度优先遍历的简单应用

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <map>
  5. #include <cmath>
  6. #include <queue>
  7. #include <stack>
  8. #include <algorithm>
  9. using namespace std;
  10. class Solution
  11. {
  12. public:
  13. int numIslands(vector<vector<char>>& g)
  14. {
  15. int count = 0;
  16. if (g.size() <= 0)
  17. return count;
  18. vector<vector<bool>> visit(g.size(),vector<bool>(g[0].size(),false));
  19. for (int i = 0; i < g.size(); i++)
  20. {
  21. for (int j = 0; j < g[0].size(); j++)
  22. {
  23. if (g[i][j] == '1' && visit[i][j] == false)
  24. {
  25. getAll(g, visit, i, j);
  26. count++;
  27. }
  28. }
  29. }
  30. return count;
  31. }
  32. void getAll(vector<vector<char>>& g, vector<vector<bool>>& visit, int x, int y)
  33. {
  34. if (x < 0 || x >= g.size() || y < 0 || y >= g[0].size())
  35. return;
  36. else
  37. {
  38. if (g[x][y] == '1' && visit[x][y]==false)
  39. {
  40. visit[x][y] = true;
  41. getAll(g, visit, x - 1, y);
  42. getAll(g, visit, x + 1, y);
  43. getAll(g, visit, x, y + 1);
  44. getAll(g, visit, x, y - 1);
  45. }
  46. }
  47. }
  48. };

发表评论

表情:
评论列表 (有 0 条评论,257人围观)

还没有评论,来说两句吧...

相关阅读