简体   繁体   中英

Number of holes in a 2d array (Python)

Consider a binary 2d array. I'm trying to count the number of connected zeros such that the shape created by these zeros is surrounded entirely by 1s (and hence, not on the boundary). I only need to know whether at least 1 hole exists in the array.

Examples of holes:

1 hole
111
101
101
111

1 hole
0000
1011
0110
1001
1011
1110

Invalid examples of holes:

101

111
001

01111
11001
10001
10001
10011
10111

I've looked at the 'number of islands' problem and connected components but I can't seem to find a way to adapt these for this problem. The main issue I'm having is making sure that when a collection of 0s includes a border digit, it is still counted as a hole.

Does anyone know what the right direction to go in would be for this problem?

Here's a complete Python program:

input = """0100
1011
0110
1011
1001
1110"""

grid = input.splitlines()

holes = 0
seen = set()

def is_in_hole(x, y):
    '''dfs'''
    seen.add((x, y))
    if grid[y][x] != '0': return True
    if y in [0, len(grid) - 1] or x in [0, len(grid[0]) - 1]: return False

    for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
        nei_x, nei_y = x + dx, y + dy
        if (nei_x, nei_y) in seen: continue
        seen.add((nei_x, nei_y))
        if not is_in_hole(nei_x, nei_y): return False

    return True

for y in range(1, len(grid) - 1):
    for x in range(1, len(grid[0]) - 1):
        if (x, y) not in seen and grid[y][x] == '0': 
            if is_in_hole(x, y): holes += 1

print(holes)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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