leetcode算法题基础(三十七) 并查集(一)200 岛屿数量
这道题的输入是一个二维数组(n ∗ m n*mn∗m),然后要我们求联通区域的块数
我的思路是创建一个一个长度为n ∗ m n*mn∗m的一维数组作为初始并查集,然后使用遍历输入的二维数组,每当发现某个位置的右边或者下面的值是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"]])
本文来自博客园,作者:秋华,转载请注明原文链接:https://www.cnblogs.com/qiu-hua/p/14004706.html