leetcode 695. Max Area of Island 岛屿的最大面积 + 十分典型的深度优先遍历DFS

迈不过友情╰ 2022-06-03 08:39 264阅读 0赞

Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

Example 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
Example 2:
[[0,0,0,0,0,0,0,0]]
Given the above grid, return 0.
Note: The length of each dimension in the given grid does not exceed 50.

本题题意很简单,就是计算面积最大的岛,直接深度优先遍历DFS即可,

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <set>
  5. #include <queue>
  6. #include <stack>
  7. #include <string>
  8. #include <climits>
  9. #include <algorithm>
  10. #include <sstream>
  11. #include <functional>
  12. #include <bitset>
  13. #include <numeric>
  14. #include <cmath>
  15. #include <regex>
  16. using namespace std;
  17. class Solution
  18. {
  19. public:
  20. int res = 0;
  21. int maxAreaOfIsland(vector<vector<int>>& grid)
  22. {
  23. int row = grid.size(), col = grid[0].size();
  24. vector<vector<bool>> visit(row, vector<bool>(col, false));
  25. for (int i = 0; i < row; i++)
  26. {
  27. for (int j = 0; j < col; j++)
  28. {
  29. if (grid[i][j] == 1)
  30. {
  31. int cur = 0;
  32. dfs(grid, visit, i, j, cur);
  33. }
  34. }
  35. }
  36. return res;
  37. }
  38. void dfs(vector<vector<int>>& a, vector<vector<bool>>& visit, int x, int y, int& cur)
  39. {
  40. int row = a.size(), col = a[0].size();
  41. if (x < 0 || x >= row || y < 0 || y >= col || a[x][y] == 0 || visit[x][y] == true)
  42. return;
  43. else
  44. {
  45. visit[x][y] = true;
  46. cur+=1;
  47. res = max(res, cur);
  48. vector<vector<int>> dirs{ { 0,-1 },{ -1,0 },{ 0,1 },{ 1,0 } };
  49. for (auto dir : dirs)
  50. dfs(a, visit, x + dir[0], y + dir[1], cur);
  51. }
  52. }
  53. };

发表评论

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

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

相关阅读