岛屿数量
    题目链接:https://leetcode-cn.com/problems/number-of-islands/
    图片.png

    思路:想法比较直接,遍历整个图碰到1就计数并用DFS或BFS沉掉目前这个岛屿上的所有陆地

    参考代码:

    1. class Solution {
    2. private:
    3. int width;
    4. int height;
    5. public:
    6. int numIslands(vector<vector<char>>& grid) {
    7. if (grid.size() == 0 || grid[0].size() == 0) {
    8. return 0;
    9. }
    10. width = grid[0].size();
    11. height = grid.size();
    12. int res = 0;
    13. for (int i = 0; i < width; ++i) {
    14. for (int j = 0; j < height; ++j) {
    15. if (grid[j][i] == '1') {
    16. sinkIsland(grid, j, i);
    17. ++res;
    18. }
    19. }
    20. }
    21. return res;
    22. }
    23. void sinkIsland(vector<vector<char>>& grid, int x, int y) {
    24. if (x < 0 || x >= height || y < 0 || y >= width || grid[x][y] == '0') {
    25. return;
    26. }
    27. grid[x][y] = '0';
    28. sinkIsland(grid, x-1, y);
    29. sinkIsland(grid, x+1, y);
    30. sinkIsland(grid, x, y-1);
    31. sinkIsland(grid, x, y+1);
    32. }
    33. };