Connected Cells in a Grid

Sort by

recency

|

266 Discussions

|

  • + 0 comments

    C++ solution using backtracking(similar to rat in a maze)

    int maze(vector<vector<int>> &matrix,int i,int j){
        if(i>=0 && i<matrix.size() && j>=0 &&
         j<matrix[0].size() && matrix[i][j]!=0){
            matrix[i][j]--;
            return (1+maze(matrix,i-1,j)+maze(matrix,i+1,j)+
            maze(matrix,i,j-1)+maze(matrix,i,j+1)+maze(matrix,i-1,j-1)+
            maze(matrix,i-1,j+1)+maze(matrix,i+1,j-1)+
            maze(matrix,i+1,j+1));
        }
        else{
            return 0;
        }
    }
    
    int connectedCell(vector<vector<int>> matrix) {
        vector<int>v;
        for(int i=0;i<matrix.size();i++){
            for(int j=0;j<matrix[0].size();j++){
                if(matrix[i][j]==1){
                    v.push_back(maze(matrix,i,j));
                }
            }
        }
        sort(v.begin(),v.end());
        if(v.empty()) return 0;
        else return v[v.size()-1];
    }
    
  • + 0 comments
    def connectedCell(matrix):
        def dfs(matrix, visited, i, j):
            # Stack for DFS
            stack = [(i, j)]
            count = 0
    
            while stack:
                x, y = stack.pop()
                if not (0 <= x < n and 0 <= y < m) or visited[x][y] or matrix[x][y] == 0:
                    continue
    
                visited[x][y] = True
                count += 1
    
                # Check all 8 possible directions
                for dx, dy in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]:
                    stack.append((x + dx, y + dy))
    
            return count
    
        n = len(matrix)
        m = len(matrix[0])
        visited = [[False] * m for _ in range(n)]
        max_region = 0
    
        for i in range(n):
            for j in range(m):
                if matrix[i][j] == 1 and not visited[i][j]:
                    size_of_region = dfs(matrix, visited, i, j)
                    max_region = max(max_region, size_of_region)
    
        return max_region
    
  • + 0 comments
    def connectedCell(matrix):
        # Write your code here
        ones = []
        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                if matrix[i][j] == 1:
                    ones.append((i, j))
        l = []
        while ones != []:
            one = ones.pop(0)
            ll = [one]
            m = 1
            n = 0
            while n != m:
                #count pre expansion
                m = len(ll)
                for one in ll:
                    i, j = one[0], one[1]
                    neighbors = [(i-1, j-1), (i-1, j), (i-1, j+1), (i, j-1), (i, j+1), (i+1, j-1), (i+1, j), (i+1, j+1)]
                    for neighbor in neighbors:
                        if neighbor in ones:
                            ones.remove(neighbor)
                            ll.append(neighbor)
                #count post expansion
                n = len(ll)
            l.append(len(ll))   
        return max(l)
    
  • + 0 comments
    from collections import deque
    
    
    def connectedCell(matrix):
        visited = [[True if cell == 0 else False for cell in row] for row in matrix]
        max_num = 0
        
        r, c = len(matrix), len(matrix[0])
        directions = ((0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (1, -1), (-1, 1), (1, 1))
        
        for i in range(r):
            for j in range(c):
                if visited[i][j]:
                    continue
                    
                # filled cell found
                count = 0
                queue = deque([(i, j)])
                visited[i][j] = True
                while queue:
                    x, y = queue.popleft()
                    count += 1
                    for dx, dy in directions:
                        nx, ny = x + dx, y + dy
                        if 0 <= nx < r and 0 <= ny < c and not visited[nx][ny]:
                            queue.append((nx, ny))
                            visited[nx][ny] = True
                
                max_num = max(max_num, count)
                
        return max_num
    
  • + 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