class Solution(object):
def numIslands(self, grid):"""
:type grid: List[List[str]]:rtype:int"""
# 1. DFS
if not grid or len(grid)==0:return0
res =0
row =len(grid)
col =len(grid[0])for i in range(0, row):for j in range(0, col):if grid[i][j]=='1':
res +=1
self.dfs(grid, i, j, row, col)return res
#dfs将遇到的‘1’与上下左右的‘1’都同化成‘0’
# 同化的为一个岛屿,避免下次重复计入岛屿数量
def dfs(self, grid, x, y, row, col):if x <0 or y <0 or x >= row or y >= col or grid[x][y]=='0':return
grid[x][y]='0'
self.dfs(grid, x, y-1, row, col)
self.dfs(grid, x, y+1, row, col)
self.dfs(grid, x-1, y, row, col)
self.dfs(grid, x+1, y, row, col)
# 2.BFS
if not grid or len(grid)==0:return0
result =0
row =len(grid)
col =len(grid[0])
que = collections.deque()for i in range(row):for j in range(col):if grid[i][j]=='1':
result +=1
# 将坐标放到队列中
que.append([i, j])
grid[i][j]='0'while que:
temp = que.popleft()
x = temp[0]
y = temp[1]if0<= x-1 and grid[x-1][y]=='1':
que.append([x-1, y])
grid[x-1][y]='0'if x+1< row and grid[x+1][y]=='1':
que.append([x+1, y])
grid[x+1][y]='0'if0<= y-1 and grid[x][y-1]=='1':
que.append([x, y-1])
grid[x][y-1]='0'if y+1< col and grid[x][y+1]=='1':
que.append([x, y+1])
grid[x][y+1]='0'return result
# 3.并查集
class UnionFind:
def __init__(self, grid):
row =len(grid)
col =len(grid[0])
self.root =[-1]*(row*col)
self.count =0
self.rank =[0]*(row*col)for i in range(row):for j in range(col):if grid[i][j]=='1':
self.root[i*col+j]= i*col+j
self.count +=1
def find(self, x):if x != self.root[x]:
self.root[x]= self.find(self.root[x])return self.root[x]
def union(self, x, y):
rootx = self.find(x)
rooty = self.find(y)if rootx != rooty:if self.rank[rootx]> self.rank[rooty]:
self.root[rooty]= rootx
elif self.rank[rootx]< self.rank[rooty]:
self.root[rootx]= rooty
else:
self.root[rooty]= rootx
self.rank[rootx]+=1
self.count -=1
def getCount(self):return self.count
class Solution(object):
def numIslands(self, grid):"""
:type grid: List[List[str]]:rtype:int"""
if not grid or len(grid)==0:return0
nr =len(grid)
nc =len(grid[0])
uf =UnionFind(grid)for i in range(nr):for j in range(nc):if grid[i][j]=='1':
grid[i][j]='0'for x, y in [(i-1, j),(i+1, j),(i, j-1),(i, j+1)]:if0<= x <nr and 0<= y < nc and grid[x][y]=='1':
uf.union(i*nc+j, x*nc+y)return uf.getCount()