0

I am trying to make a function that given a 2d array of either 0's or 1's and a set of coordinates, returns the area of the selected region with the same value as the given coordinates.

For example given the array:

[[0, 1, 0, 0, 0],
 [0, 1, 0, 0, 0],
 [0, 1, 0, 0, 0],
 [0, 1, 0, 0, 0],
 [0, 1, 0, 0, 0]]

and the coordinates [0,0], it would return 5.

I have tried a simple DFS but am running into issues where it runs over the same spots multiple times, returning an abnormally large area like 330.

sjpratt
  • 76
  • 1
  • 7
  • To make sure I understand correctly, `[0,1]` should return `5`, `[0,2]` should return `15`, and `[3,3]` should return `15` as well? Are areas connected diagonally as well? Building your own go engine using numpy? – Jan Christoph Terasa Nov 26 '19 at 07:53
  • That's the idea, yes. In my implementation it would only look up, down, left, and right – sjpratt Nov 27 '19 at 20:04

1 Answers1

0

I actually figured this one out!

Basically it follows a BFS search looking only up, down, left, and right.

The part on finding the neighbours was taken from this answer to another question.

def find_area(arr, x, y):
    queue = [(x,y)]
    visited = []
    w = len(arr[0])
    h = len(arr)
    area = 0
    while len(queue) != 0:
        curr = queue.pop(0)
        print(curr)
        x = curr[0]
        y = curr[1]
        if arr[curr[0]][curr[1]] == 0 and curr not in visited:
            area += 1
            visited.append(curr)
            neighbors = [(x+a[0], y+a[1]) 
                            for a in [(-1,0), (1,0), (0,-1), (0,1)] 
                            if ((0 <= x+a[0] < w) and (0 <= y+a[1] < h))]
            for i in neighbors:
                if i not in visited:
                    queue.append(i)
    return area
sjpratt
  • 76
  • 1
  • 7