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

题目链接:https://leetcode.com/problems/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:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3


思路:比较简单的DFS,用一个标记位来标记是不是这一位被访问过了,然后依次对数组中的每一个未被访问过的且值为'1'的元素为起始点做DFS,标记所有和其相邻的'1'.

代码如下:

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


你可能感兴趣的:(LeetCode,Google,hash,Facebook,DFS)