leetcode No200. Number of Islands

Question:

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:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

Algorithm:

DFS,从边界找,如果是1,则让它的上下左右都为0,然后count++,

Accepted Code:

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if(grid.empty())
            return 0;
        int M=grid.size();
        int N=grid[0].size();
        int res=0;
        for(int i=0;i<M;i++)
            for(int j=0;j<N;j++)
                if(grid[i][j]=='1'){
                    DFS(grid,i,j);
                    res++;
                }
        return res;
    }
    void DFS(vector<vector<char>>& grid,int i,int j){
        int M=grid.size();
        int N=grid[0].size();
        grid[i][j]='0';
        if(i>0 && grid[i-1][j]=='1')
            DFS(grid,i-1,j);
        if(i<M-1 && grid[i+1][j]=='1')
            DFS(grid,i+1,j);
        if(j>0 && grid[i][j-1]=='1')
            DFS(grid,i,j-1);
        if(j<N-1 && grid[i][j+1]=='1')
            DFS(grid,i,j+1);
    }
};


你可能感兴趣的:(LeetCode)