leetcode 200. Number of Islands

382 阅读1分钟
  1. Number of Islands Medium

5680

193

Add to List

Share 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: grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] Output: 1 Example 2:

Input: grid = [ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ] Output: 3

思路: 1.最外层双层遍历寻找为1的位置,找到之后,count++ 2.dfs,寻找上下左右方向的值,为1时置为0

代码:python3

class Solution:
    def numIslands(self, grid):
        count=0
        def dfs(grid,r,c):
            grid[r][c]="0"
            if r+1<len(grid) and grid[r+1][c] is "1":
                dfs(grid,r+1,c)
            if r>0 and grid[r-1][c] is "1":
                dfs(grid,r-1,c)
            if c+1<len(grid[0]) and grid[r][c+1] is "1":
                dfs(grid,r,c+1)
            if c>0 and grid[r][c-1] is "1":
                dfs(grid,r,c-1)
                    
        for r in range(len(grid)):
            for c in range(len(grid[0])):
                if grid[r][c] is "1":
                    count=count+1
                    print(count)
                    dfs(grid,r,c)
        return count
if __name__ == '__main__':
    print(Solution().numIslands([["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]))

时间复杂度:O(m^2) 空间复杂度:O(m^2)