zoukankan      html  css  js  c++  java
  • Leetcode 200. Number of Islands

    https://leetcode.com/problems/number-of-islands/

    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:

    Input:
    11110
    11010
    11000
    00000
    
    Output: 1
    

    Example 2:

    Input:
    11000
    11000
    00100
    00011
    
    Output: 3

    • DFS / BFS经典题目。从一个点开始扩展,把所有连通的点都标记为已访问,这些点都属于一个岛。搜索题目就是要确定策略套模版。
    • 注意时间空间复杂度都是O(m * n)。最坏情况下每个点都访问到。
     1 class Solution:
     2     def numIslands(self, grid: List[List[str]]) -> int:
     3         if not grid:
     4             return 0
     5         
     6         self.x = len(grid)
     7         self.y = len(grid[0])
     8         count = 0
     9         
    10         for i in range(self.x):
    11             for j in range(self.y):
    12                 if grid[i][j] == '1':
    13                     self.DFS(grid, i, j)
    14                     count += 1
    15         
    16         return count
    17                 
    18     def DFS(self, g: List[List[str]], x: int, y: int):
    19         if x < 0 or x >= self.x or y < 0 or y >= self.y or g[x][y] == '0':
    20             return
    21         
    22         g[x][y] = '0'
    23         
    24         self.DFS(g, x - 1, y)
    25         self.DFS(g, x + 1, y)
    26         self.DFS(g, x, y - 1)
    27         self.DFS(g, x, y + 1)
    View Python Code
  • 相关阅读:
    1219 总结
    1206 冲刺三
    1130 冲刺2
    1128 主页面
    1123 冲刺3
    1121 冲刺2
    1118 冲刺1
    1117 新冲刺
    0622 软件工程总结
    0617 实验四 主存空间的分配和回收
  • 原文地址:https://www.cnblogs.com/pegasus923/p/11271355.html
Copyright © 2011-2022 走看看