[LeetCode 解题报告]200. Number of Islands

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:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3
class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if (grid.empty() || grid[0].empty())
            return 0;
        
        int row = grid.size(), col = grid[0].size();
        int res = 0;
        
        vector<vector<bool>> isVisited(row, vector<bool>(col, false));
        for (int i = 0; i < row; i ++) {
            for (int j = 0; j < col; j ++) {
                if (grid[i][j] == '1' && !isVisited[i][j]) {
                    numIslandsDFS(grid, isVisited, i, j);
                    res ++;
                }
            }
        }
        return res;
    }
    
    void numIslandsDFS(vector<vector<char>>& grid, vector<vector<bool>>& isVisited, int row, int col) {
        if (row < 0 || row >= grid.size() || col < 0 || col >= grid[0].size())
            return ;
        
        if (grid[row][col] == '0' || isVisited[row][col])
            return ;
        
        isVisited[row][col] = true;
        numIslandsDFS(grid, isVisited, row-1, col);
        numIslandsDFS(grid, isVisited, row+1, col);
        numIslandsDFS(grid, isVisited, row, col-1);
        numIslandsDFS(grid, isVisited, row, col+1);
    }
    
};
发布了467 篇原创文章 · 获赞 40 · 访问量 45万+

猜你喜欢

转载自blog.csdn.net/caicaiatnbu/article/details/104158552