1. 题目
给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 1:
输入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1
示例 2:
输入:grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
输出:3
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] 的值为 '0' 或 '1'
2. 题解
# 200
from typing import List
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if grid is None or len(grid) == 0:
return 0
row = len(grid)
col = len(grid[0])
water = 0
uf = UnionFind(grid)
for i in range(0, row):
for j in range(0, col):
if grid[i][j] == "0":
water += 1
else:
directions = [[0,1], [0,-1], [-1,0],[1,0]]
for d in directions:
x = i + d[0]
y = j + d[1]
if 0 <= x < row and 0 <= y < col and grid[x][y] == "1":
uf.union(i * col + j, x * col + y)
return uf.getCount() - water
class UnionFind:
def __init__(self, grid):
self.row = len(grid)
self.col = len(grid[0])
self.count = self.row * self.col
self.root = [-1] * (self.row * self.col)
for i in range(0, len(self.root)):
self.root[i] = i
def find(self, x) -> int:
if x == self.root[x]:
return x
else:
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:
self.root[rootx] =rooty
self.count = self.count - 1
def getCount(self) -> int:
return self.count