简体   繁体   English

图遍历计数云[python]

[英]Graph Traversal count clouds [python]

Given a 2D grid skyMap composed of '1's (clouds) and '0's (clear sky), count the number of clouds. 给定一个由“ 1”(云)和“ 0”(晴空)组成的2D网格skyMap,计算云的数量。

A cloud is surrounded by clear sky, and is formed by connecting adjacent clouds horizontally or vertically. 云被晴朗的天空包围,并通过水平或垂直连接相邻的云而形成。 You can assume that all four edges of the skyMap are surrounded by clear sky. 您可以假设skyMap的所有四个边缘都被晴朗的天空包围。

Example

skyMap = [['0', '1', '1', '0', '1'],
          ['0', '1', '1', '1', '1'],
          ['0', '0', '0', '0', '1'],
          ['1', '0', '0', '1', '1']]

the output should be 输出应该是

countClouds(skyMap) = 2;

For 对于

skyMap = [['0', '1', '0', '0', '1'],
          ['1', '1', '0', '0', '0'],
          ['0', '0', '1', '0', '1'],
          ['0', '0', '1', '1', '0'],
          ['1', '0', '1', '1', '0']]

the output should be 输出应该是

countClouds(skyMap) = 5.

This can be solved by computing connected components directly on the sky map matrix. 这可以通过直接在天空地图矩阵上计算连接的组件来解决。 We can use the data structure of Disjoint-set . 我们可以使用Disjoint-set的数据结构。

In this example, the implementation of Disjoint-set ( UnionFind ) is taken from here : 在此示例中,不相交集( UnionFind )的实现来自此处

refs = [[0, 0], [-1, 0], [0, -1], [1, 0], [0, 1]]
for i in range(len(skyMap)):
    for j in range(len(skyMap[i])):
        print i, j
        for dy, dx in refs:
            is_neighbour_valid = 0 <= (i + dy) < len(skyMap) and 0 <= (j + dx) < len(skyMap[i])
            if not is_neighbour_valid:
                continue

            current_cell, neighbour_cell = skyMap[i][j] == '1', skyMap[i + dy][j + dx] == '1'
            if current_cell and is_neighbour_valid:
                ds.union((i, j), (i + dy, j + dx))

# The number of connected components:
print len(set(ds.parents.values()))

For every entry with value '1' we create a set. 对于每个值为'1'条目,我们创建一个集合。 If it is adjacent to another such entry, we unite the two sets. 如果它与另一个这样的条目相邻,我们将这两个集合结合在一起。 At the end, we get a set of disjoint sets, and each one represents a cloud. 最后,我们得到了一组不相交的集合,每个集合代表一个云。 In this code, ds.parents gives us access to the clouds' "representatives", so we can tell the number of clouds. 在此代码中, ds.parents使我们可以访问云的“代表”,因此我们可以确定云的数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM