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