Python - Determine Matrix cells are a group -


given set of tuples represent position in matrix.

for example {(1, 2), (1, 3), (2, 2), (0, 3), (0, 4)} 

where tuple (r,k) represents row r , column k. how can determine if hang together?

examples  {(1, 2), (1, 3), (2, 2), (0, 3), (0, 4)} => hangs {(1, 2), (1, 4), (2, 2), (0, 3), (0, 4)} => doesnt hang 

i'd simple bfs or dfs, example:

def connected(cells):     if cells:         cells = cells.copy()         stack = [cells.pop()]         while stack:             i, j = stack.pop()             neighbors = {(i-1, j), (i+1, j), (i, j-1), (i, j+1)} & cells             stack.extend(neighbors)             cells -= neighbors     return not cells 

usage/demo:

for cells in ({(1, 2), (1, 3), (2, 2), (0, 3), (0, 4)},               {(1, 2), (1, 4), (2, 2), (0, 3), (0, 4)}):     print(connected(cells)) 

prints:

true false 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -