200. Number of Islands

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: 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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-islands
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Think and method:
So if we think about this problem, we can abstract the actual problem to determine that there are sets of disconnected ones in a two-dimensional grid, because by definition 1 is an island and 0 is a body of water.Confused at first, not sure where to start until you remember the depth-first search

1, DFS
We could scan the entire two-dimensional grid graph, if every found a 1, then it means that have found an island, we take the position as the starting position of depth-first search, in order not to affect the possible existence of judging is not connected to island, avoid double counting the same island, we will be in the process of depth-first search 1 tag is 0
When we perform the entire outer loop, we record the number of DFS, which is the number of islands.

Time complexity: O(MN), where M and N are the number of rows and columns respectively.
Space complexity: O(MN),

2.BFS
Correspondingly, we can also replace the intermediate process with BFS, which will not be repeated here

Time complexity: O(MN)
Space complexity: O(min(M, N))

3. Check the collection
Learning from the official documents, we can scan the entire two-dimensional grid to figure out the number of islands.If a position is 11, it is combined with 11 in the adjacent four directions in the parallel lookup set.The final number of islands is the number of connected components in the cluster.

Time complexity: O(MN∗ (MN)), while (x) is an anti-Ackerman function and can be treated as a constant time complexity
Space complexity: O(MN)

Code:
1

func numIslands(grid [][]byte) int {
   
    if len(grid) == 0{
   return 0}
    row, column := len(grid), len(grid[0])
    var count int

    for x := 0; x < row; x++{
   
        for y := 0; y < column
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值