Connected Cells in a Grid

  • + 0 comments

    JavaScript solution inspired by other folks

    function connectedCell(matrix) {
      let largestArea = 0;
      const rows = matrix.length;
      const cols = matrix[0].length;
    
      for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
          if (matrix[i][j] === 1) {
            depthFirstSearch(matrix, i, j, 0); // Start with area as 0
          }
        }
      }
    
      function depthFirstSearch(matrix, i, j, currentCell) {
        if (i < 0 || i >= rows || j < 0 || j >= cols || matrix[i][j] === 0) {
          return;
        }
    
        currentCell++;
        largestArea = Math.max(largestArea, currentCell);
        matrix[i][j] = 0;
    
        // Upper Row
        depthFirstSearch(matrix, i - 1, j - 1, currentCell);
        depthFirstSearch(matrix, i - 1, j, currentCell);
        depthFirstSearch(matrix, i - 1, j + 1, currentCell);
    
        // Current Row
        depthFirstSearch(matrix, i, j - 1, currentCell);
        depthFirstSearch(matrix, i, j + 1, currentCell);
    
        // Lower Row
        depthFirstSearch(matrix, i + 1, j - 1, currentCell);
        depthFirstSearch(matrix, i + 1, j, currentCell);
        depthFirstSearch(matrix, i + 1, j + 1, currentCell);
    
        matrix[i][j] = 1;
      }
    
      return largestArea;
    }