这几天刷一下并查集的题目,这道题目是这样的
给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
示例 1:
输入:
11110
11010
11000
00000
输出: 1
示例 2:
输入:
11000
11000
00100
00011
输出: 3
这道题的输入是一个二维数组(),然后要我们求联通区域的块数
我的思路是创建一个一个长度为的一维数组作为初始并查集,然后使用遍历输入的二维数组,每当发现某个位置的右边或者下面的值是1,并且本身的值也是1的时候,合并这两个区域。(注意二维数组的索引不要搞混,我写的时候搞混导致调试了很久)
代码如下
class Solution(object):
#创建初始并查集
def __init__(self):
self.ans = [i for i in range(100000)]
#查
def find(self, x):
while self.ans[x] != x:
x = self.ans[x]
return x
#并
def merge(self, i, j):
fi = self.find(i)
fj = self.find(j)
if self.ans[fi] != self.ans[fj]:
self.ans[fi] = fj
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
for i in range(len(grid)):
for j in range(len(grid[i])):
t1 = i*len(grid[0])+j
t2 = t1+1
t3 = t1+len(grid[0])
if j+1<len(grid[0]) and grid[i][j] == "1" and grid[i][j+1] == "1":
self.merge(t1, t2)
if i+1<len(grid) and grid[i][j] == "1" and grid[i+1][j] == "1":
self.merge(t1, t3)
# print(self.ans[:(len(grid)*len(grid[0]))])
answer = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if self.ans[i*len(grid[0])+j] == i*len(grid[0])+j and grid[i][j] == "1":
answer += 1
return answer
# s = Solution()
# ans = s.numIslands(
# [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]])
不管是写工程代码还是写题的时候,一定要现有比较明确的思路在进行书写。