leetcode 200. Number of Islands

不念不忘少年蓝@ 2022-07-27 14:57 259阅读 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:

  1. 11110
  2. 11010
  3. 11000
  4. 00000

Answer: 1

Example 2:

  1. 11000
  2. 11000
  3. 00100
  4. 00011

Answer: 3

找最大联通量

  1. class Solution {
  2. public:
  3. int numIslands(vector<vector<char>>& grid) {
  4. if (grid.empty() || grid[0].empty())
  5. return 0;
  6. int cnt = 0;
  7. for (int i = 0; i < grid.size(); i++)
  8. {
  9. for (int j = 0; j < grid[0].size(); j++)
  10. {
  11. if (grid[i][j] == '1')
  12. {
  13. cnt++;
  14. vector<pair<int, int>>quene;//(x,y)
  15. grid[i][j] = '0';
  16. quene.push_back(pair<int, int>(j, i));
  17. while (!quene.empty())
  18. {
  19. int x = quene.back().first;
  20. int y = quene.back().second;
  21. quene.pop_back();
  22. if (x - 1 >= 0 && grid[y][x - 1] == '1')
  23. {
  24. grid[y][x - 1] = '0';
  25. quene.push_back(pair<int, int>(x - 1, y));
  26. }
  27. if (y - 1 >= 0 && grid[y-1][x ] == '1')
  28. {
  29. grid[y-1][x] = '0';
  30. quene.push_back(pair<int, int>(x , y-1));
  31. }
  32. if (x + 1 <grid[0].size() && grid[y][x + 1] == '1')
  33. {
  34. grid[y][x + 1] = '0';
  35. quene.push_back(pair<int, int>(x + 1, y));
  36. }
  37. if (y + 1 <grid.size() && grid[y+1][x] == '1')
  38. {
  39. grid[y+1][x] = '0';
  40. quene.push_back(pair<int, int>(x, y+1));
  41. }
  42. }
  43. }
  44. }
  45. }
  46. return cnt;
  47. }
  48. };

accepted

发表评论

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

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

相关阅读