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

Reference Answer

思路分析

我们遍历矩阵的每一个点,对每个点都尝试进行一次深度优先搜索,如果搜索到1,就继续向它的四周搜索。同时我们每找到一个1,就将其标为0,这样就能把整个岛屿变成0。我们只要记录对矩阵遍历时能进入多少次搜索,就代表有多少个岛屿。

这道题开始想成用动态规划求解,设置了mark_grid,进行求解遍历事实上,动态规划很难进行求解,如开始对第一行及第一列进行遍历判别,然后会存在以下形式不满足:

Input:
111
010
111
Output: 1(却被程序判别为2,因为把左下角当做一个独立岛屿看待了)

而当先对左上角、左下角与右上角进行设置后,依旧不满足,因为存在

Input:
11
Output: 1(却被程序判别为2,因为把右上角当做一个独立岛屿看待了)

最后,放弃动态规划,改用DFS。

Code

class Solution(object):
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        
        if not grid:
            return 0
        rows = len(grid)
        cols = len(grid[0])

        res = 0
        
        for row in range(rows):
            for col in range(cols):
                if grid[row][col] == '1':
                    self.explore(grid, row, col)
                    res += 1
                    
        return res
        
    def explore(self, grid, row, col):
        grid[row][col] = '0'
        if row > 0 and grid[row-1][col] == '1':
            self.explore(grid, row-1, col)
        if col > 0 and grid[row][col-1] == '1':
            self.explore(grid, row, col-1)
        if row < len(grid)-1 and grid[row+1][col] == '1':
            self.explore(grid, row+1, col)
        if col < len(grid[0])-1 and grid[row][col+1] == '1':
            self.explore(grid, row, col+1)
             

Note:

  • 动态规划与DFS到底用哪个要仔细琢磨清楚!

参考资料

[1] https://segmentfault.com/a/1190000003753307

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/84726681
今日推荐