岛屿数量
题目链接:https://leetcode-cn.com/problems/number-of-islands/
思路:想法比较直接,遍历整个图碰到1就计数并用DFS或BFS沉掉目前这个岛屿上的所有陆地
参考代码:
class Solution {private:int width;int height;public:int numIslands(vector<vector<char>>& grid) {if (grid.size() == 0 || grid[0].size() == 0) {return 0;}width = grid[0].size();height = grid.size();int res = 0;for (int i = 0; i < width; ++i) {for (int j = 0; j < height; ++j) {if (grid[j][i] == '1') {sinkIsland(grid, j, i);++res;}}}return res;}void sinkIsland(vector<vector<char>>& grid, int x, int y) {if (x < 0 || x >= height || y < 0 || y >= width || grid[x][y] == '0') {return;}grid[x][y] = '0';sinkIsland(grid, x-1, y);sinkIsland(grid, x+1, y);sinkIsland(grid, x, y-1);sinkIsland(grid, x, y+1);}};
