深度优先搜索算法:
根据一个点‘1’扩展到周围四个节点,并将节点置为‘0’,依次进行此操作;每发现一个‘1’,则岛屿个数加一。
class Solution { private: void dfs(vector<vector<char>> &grid, int r, int c) { int nr = grid.size(); int nc = grid[0].size(); grid[r][c] = '0'; if (r-1 >= 0 && grid[r-1][c] == '1') dfs(grid, r-1, c); if (r+1 < nr && grid[r+1][c] == '1') dfs(grid, r+1, c); if (c-1 >= 0 && grid[r][c-1] == '1') dfs(grid, r, c-1); if (c+1 < nc && grid[r][c+1] == '1') dfs(grid, r, c+1); } public: int numIslands(vector<vector<char>> & grid) { int r = grid.size(); int c = grid[0].size(); int ans = 0; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (grid[i][j] == '1') { ans++; dfs(grid, i, j); } } } return ans; } };
时间复杂度为O(m*n)
空间复杂度为O(m*n)