LeetCode:Number of Islands

Number of Islands

Total Accepted: 31504  Total Submissions: 122317  Difficulty: Medium

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Hide Tags
  Depth-first Search Breadth-first Search Union Find




































思路:

dfs搜索4个方向,将1->0即可。


code:

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


你可能感兴趣的:(LeetCode,number,of,Islands)