Semzem
Semzem

Reputation: 93

Detect Cyclic Islands on a Matrix

On a binary matrix M, a cyclic island is a region of 1s where the region encircles itself (horizontal, vertical and cross directions are allowed)

Given a matrix M,

Allowing neighbors to be in any of the following directions:

directions = [(-1,-1), (-1,0), (-1,1), (0,1), (1,1), (1,0), (1,-1), (0,-1)]
  1. Return all of the cyclic islands on this matrix M.
  2. If there are cyclic islands, turn these cyclic islands in to regular islands by turning inner area of the cycle into 1s and return the result
  3. If there are no cyclic islands return the matrix M

Example:

M = 
[[0, 0, 1, 0, 0, 0, 1, 0],
 [0, 1, 0, 1, 0, 0, 0, 0],
 [0, 1, 1, 1, 0, 0, 0, 0],
 [0, 0, 1, 0, 1, 1, 0, 0],
 [0, 0, 0, 1, 0, 0, 1, 0],
 [0, 0, 1, 0, 0, 0, 0, 1],
 [0, 0, 0, 1, 0, 0, 1, 0],
 [0, 0, 0, 0, 1, 1, 0, 0]]

has 3 cyclic islands located at indices. While the islands can be defined in various ways, one example would be

a = [[0, 2], [1, 1], [1, 3], [2, 1], [2, 2], [2, 3]] 
b = [[2, 3], [3, 2], [3, 4], [4, 3]]
c = [[3, 4], [3, 5], [4, 3], [4, 6], [5, 2], [5, 7], [6, 3], [6, 6], [7, 4], [7, 5]]

And filling the inside of the islands would return

Output = 
[[0, 0, 1, 0, 0, 0, 1, 0],
 [0, 1, 1, 1, 0, 0, 0, 0],
 [0, 1, 1, 1, 0, 0, 0, 0],
 [0, 0, 1, 1, 1, 1, 0, 0],
 [0, 0, 0, 1, 1, 1, 1, 0],
 [0, 0, 1, 1, 1, 1, 1, 1],
 [0, 0, 0, 1, 1, 1, 1, 0],
 [0, 0, 0, 0, 1, 1, 0, 0]]

I know that DFS will be needed to find the cycles, but I can only find neighbors for each index, unable to make the connection as to how this will help me get the cycles. Given the neighbors of each index, this should create a graph since the connection is an undirected edge, but the rest seems beyond me...

To find neighbors:

M = [
 [0, 0, 1, 0, 0, 0, 1, 0],
 [0, 1, 1, 1, 0, 0, 0, 0],
 [0, 1, 1, 1, 0, 0, 0, 0],
 [0, 0, 1, 1, 1, 1, 0, 0],
 [0, 0, 0, 1, 1, 1, 1, 0],
 [0, 0, 1, 1, 1, 1, 1, 1],
 [0, 0, 0, 1, 1, 1, 1, 0],
 [0, 0, 0, 0, 1, 1, 0, 0]]

indices = []
for i in range(len(M)):
    for j in range(len(M[0])):
        if M[i][j] == 1:
            indices.append([i,j])

directions = [(-1,-1), (-1,0), (-1,1), (0,1), (1,1), (1,0), (1,-1), (0,-1)]


neighbors = {}
while indices:
    init = indices.pop()
    current_circle = [init]
    tracker = [init]
    
    while current_circle:
        x, y = current_circle.pop()
        neighbors[(x,y)] = []
        ctr = 0
        for (i, j) in directions:
            xi, yj = x+i, y+j 
            if [xi, yj] in indices:
                current_circle.append([xi, yj])
                tracker.append([xi, yj])
                indices.remove([xi, yj])
                neighbors[(x,y)].append([xi, yj])
            elif [xi, yj] in tracker:
                neighbors[(x,y)].append([xi, yj])
     
neighbors

But I am blank after this. Any help would be much appreciated.

Upvotes: 0

Views: 50

Answers (0)

Related Questions