Leetcode 200. Number of Islands深度优先搜索DFS

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

题目链接:https://leetcode.com/problems/number-of-islands/

class Solution {
public:
    
   void DFS(vector<vector<char>>&grid,int m,int n)
    {
        grid[m][n]='0';
       if(m!=0&&grid[m-1][n]=='1')//上面
           DFS(grid,m-1,n);
        if(m!=grid.size()-1&&grid[m+1][n]=='1')//下面
            DFS(grid,m+1,n);
       if(n!=0&&grid[m][n-1]=='1')//左面
           DFS(grid,m,n-1);
       if(n!=grid[0].size()-1&&grid[m][n+1]=='1')//右面
            DFS(grid,m,n+1);
    }
    int numIslands(vector<vector<char>>& grid) {
        int res=0;
        int m=grid.size();
        if(m==0)
            return res;
        int n=grid[0].size();
        if(n==0)
            return res;
        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;
    }
};

猜你喜欢

转载自blog.csdn.net/salmonwilliam/article/details/88553123