Algorithms & Data Structure (X): disjoint-set

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_18310041/article/details/100312405

leetcode: 200. The number of islands

Description of the problem: Given a two-dimensional grid by a '1' (land) and '0' (water) composition, the number of islands is calculated. An island surrounded by water, and it is through the horizontal or vertical direction is connected to each adjacent land. You can assume that the water surrounding the four sides of the grid are.

Solution: disjoint-set, if the current point is 1, compared with a neighboring node merged into the same collection. Query collections need to be traversed to the top of.

Time complexity: 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)
        

 

Guess you like

Origin blog.csdn.net/qq_18310041/article/details/100312405