2015-06-04 37 views
0

給定一組元組來表示矩陣中的位置。Python - 確定矩陣單元格是一組

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

其中元組(r,k)表示行r和列k。 我怎樣才能確定他們是否一起掛?

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

你是什麼意思通過「掛在一起」? –

回答

1

我只是做簡單的BFS或DFS,例如:

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 

用法/演示:

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)) 

打印:

True 
False 
+0

謝謝你:) – Domien