200. Number of Islands

这篇博客讨论了LeetCode第200题——数岛问题,即在一个二维网格中计算陆地的数量。博主分析了三种不同的解决方法:深度优先搜索(DFS)、广度优先搜索(BFS)和使用并查集。每种方法的时间复杂度和空间复杂度都进行了说明,并提供了代码实现的思考。最后,博主提到了在实际代码实现中DFS的简洁性和高效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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; y++{
        // begin dfs
            if grid[x][y] == '1'{
                count++
                dfs(x, y, grid)
            }
        }
    }
    return count
}

func dfs(x, y int, grid [][]byte){
    //end condition
    if x < 0 || y < 0 || x >= len(grid) || y >= len(grid[0]) || grid[x][y] == '0'{
        return 
    }
    //refresh the 1 with 0
    grid[x][y] = '0'
    dfs(x + 1, y, grid)
    dfs(x - 1, y, grid)
    dfs(x, y + 1, grid)
    dfs(x, y - 1, grid)
}

3
本人的实现出现一些问题,参考了该作者的代码

var n int
var m int

func numIslands(grid [][]byte) int {
	n = len(grid)
	if n < 1 {
		return 0
	}

	m = len(grid[0])
	root := make([]int, n*m)
	rank := make([]int, n*m)
	count := 0
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if grid[i][j] == '1' {
				count++
				root[i*m+j] = i*m + j
				rank[i*m+j] = 0
			}
		}
	}

	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if grid[i][j] == '1' {
				grid[i][j] = '0'
				if i+1 < n && grid[i+1][j] == '1' {
					count = unite(i*m+j, (i+1)*m+j, count, root,rank)
				}
				if j+1 < m && grid[i][j+1] == '1' {
					count = unite(i*m+j, i*m+j+1, count, root,rank)
				}
				// if i-1 >= 0 && grid[i-1][j] == '1' {
				// 	count = unite(i*m+j, (i-1)*m+j, count, root)
				// }
				// if j-1 >= m && grid[i][j-1] == '1' {
				// 	count = unite(i*m+j, i*m+j-1, count, root)
				// }
			}
		}
	}
	return count
}

func find_root(x int,root []int)  int{
	if(root[x] == x){
        return x
	}else{
		return find_root(root[x],root)
	}
}

func unite(x, y, count int, root []int,rank []int) int {
	root_x := find_root(x,root)
	root_y := find_root(y,root)
	if(root_x != root_y){
        if rank[root_x] > rank[root_y] {
			root[root_y] =root_x
		}else if(rank[root_x] < rank[root_y] ){
			root[root_x] =root_y
		}else{
			root[root_x] =root_y
            rank[root_y]++
		}
		count--
	}
	return count
}


作者:lao-si-pan-ju
链接:https://leetcode-cn.com/problems/number-of-islands/solution/bing-cha-ji-by-lao-si-pan-ju/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Test:
Input: grid = [
[“1”,“1”,“1”,“1”,“0”],
[“1”,“1”,“0”,“1”,“0”],
[“1”,“1”,“0”,“0”,“0”],
[“0”,“0”,“0”,“0”,“0”]
]
Output:
在这里插入图片描述

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:
在这里插入图片描述
本问题的三种解法时间效率相仿都比较优异,从理论上来说BFS空间效率最高,在代码实现上来说DFS比较简洁,且熟练

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值