leetcode:200. 岛屿数量
问题描述:给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
解法:并查集,如果当前点为1,则为1相邻节点合并到同一集合。集合的查询需要遍历到顶点为止。
时间复杂度:O(n*n)
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if not grid:
return 0
m = len(grid)
n = len(grid[0])
dict1 = {}
# 查
# 如果x不存在字典里,则创建{x: x}
# 如果f[x]=y,则创建{y: y}
def find(x):
# setdefault() 取出一个不存在的键的值(返回默认键的值,并且将新的键值保存在字典中)
dict1.setdefault(x, x)
if dict1[x] != x:
dict1[x] = find(dict1[x])
return dict1[x]
# 并
# parent[x] = y or parent[y] = x
def union(x, y):
dict1[find(x)] = find(y)
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
# 右、下方向
if 0 <= i+1 < m and grid[i+1][j] == '1':
union(i*n+j, (i+1)*n+j)
if 0 <= j+1 < n and grid[i][j+1] == '1':
union(i*n+j, i*n+j+1)
ans = set()
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
ans.add(find(i*n+j))
return len(ans)