Connected Cells in a Grid

  • + 0 comments

    Solution using OO approach

    class Cell:   
        def __init__(self, x, y, value, board):
            self.x = x
            self.y = y
            self.value = value
            self.board = board
            self.visited = False
        
        def __str__(self):
            return str(self.x) + "-" + str(self.y) + ":" + str(self.value)
            
        def isEmpty(self):
            return self.value == 0
        
        def setVisited(self, value):
            self.visited = value 
            
        def isVisited(self):
            return self.visited
            
        def connectedSibling(self):
            if ( self.isEmpty() ):
                return {}
            else:
                siblings = {}
                for i in range(-1, 2):
                    for j in range(-1, 2):
                        if i == 0 and j == 0:
                            continue  
                        nextSibling = self.board.getCell ( self.x+i, self.y+j)                    
                        if nextSibling != None:
                            if not nextSibling.isEmpty() and not nextSibling.isVisited():                                                
                                nextSibling.setVisited (True)
                                siblings[ str(self.x+i)+"_"+str(self.y+j) ] = nextSibling
                                #Verifico se ha celle adiacenti:
                                sibOfSib = nextSibling.connectedSibling()
                                for sOfs in sibOfSib.keys():
                                    siblings[sOfs] = sibOfSib[sOfs]
                            
                siblings[ str(self.x)+"_"+str(self.y) ] = self  
            return siblings
            
          
    class Board: 
        cells = {}
        
        def __init__(self, matrix):
            for row in range( len(matrix) ):
                for col in range(len( matrix[row] )):
                    self.cells[ str( row )+"_"+str(col) ] = Cell(row, col, matrix[row][col], self)
    
        def getCell(self, x, y):
            try:
                return self.cells[str(x)+"_"+str(y)]
            except KeyError:
                return None
                
        def getCells(self):
            return self.cells
        
        
                            
                
    def connectedCell(matrix):
        # Write your code here
        #print ( matrix )
        
        board = Board(matrix)
            
        cells = board.getCells()
        
        maxConnected = 0
        for c in cells.values():        
            connected = c.connectedSibling()
            if maxConnected < len(connected ):
                maxConnected = len(connected )
                
        return maxConnected