Skip to main content

Sum of Remoteness of All Cells - Solution & Explanation

MediumPremiumFree on FleetCodeArrayHash TableDepth-First SearchBreadth-First Search10 min readAsked at: Medianet
Practice this problem

Problem Statement

You are given a 0-indexed matrix grid of order n * n. Each cell in this matrix has a value grid[i][j], which is either a positive integer or -1 representing a blocked cell.

You can move from a non-blocked cell to any non-blocked cell that shares an edge.

For any cell (i, j), we represent its remoteness as R[i][j] which is defined as the following:

  • If the cell (i, j) is a non-blocked cell, R[i][j] is the sum of the values grid[x][y] such that there is no path from the non-blocked cell (x, y) to the cell (i, j).
  • For blocked cells, R[i][j] == 0.

Return the sum of R[i][j] over all cells.

 

Example 1:

Input: grid = [[-1,1,-1],[5,-1,4],[-1,3,-1]]
Output: 39
Explanation: In the picture above, there are four grids. The top-left grid contains the initial values in the grid. Blocked cells are colored black, and other cells get their values as it is in the input. In the top-right grid, you can see the value of R[i][j] for all cells. So the answer would be the sum of them. That is: 0 + 12 + 0 + 8 + 0 + 9 + 0 + 10 + 0 = 39.
Let's jump on the bottom-left grid in the above picture and calculate R[0][1] (the target cell is colored green). We should sum up the value of cells that can't be reached by the cell (0, 1). These cells are colored yellow in this grid. So R[0][1] = 5 + 4 + 3 = 12.
Now let's jump on the bottom-right grid in the above picture and calculate R[1][2] (the target cell is colored green). We should sum up the value of cells that can't be reached by the cell (1, 2). These cells are colored yellow in this grid. So R[1][2] = 1 + 5 + 3 = 9.

Example 2:

Input: grid = [[-1,3,4],[-1,-1,-1],[3,-1,-1]]
Output: 13
Explanation: In the picture above, there are four grids. The top-left grid contains the initial values in the grid. Blocked cells are colored black, and other cells get their values as it is in the input. In the top-right grid, you can see the value of R[i][j] for all cells. So the answer would be the sum of them. That is: 3 + 3 + 0 + 0 + 0 + 0 + 7 + 0 + 0 = 13.
Let's jump on the bottom-left grid in the above picture and calculate R[0][2] (the target cell is colored green). We should sum up the value of cells that can't be reached by the cell (0, 2). This cell is colored yellow in this grid. So R[0][2] = 3.
Now let's jump on the bottom-right grid in the above picture and calculate R[2][0] (the target cell is colored green). We should sum up the value of cells that can't be reached by the cell (2, 0). These cells are colored yellow in this grid. So R[2][0] = 3 + 4 = 7.

Example 3:

Input: grid = [[1]]
Output: 0
Explanation: Since there are no other cells than (0, 0), R[0][0] is equal to 0. So the sum of R[i][j] over all cells would be 0.

 

Constraints:

  • 1 <= n <= 300
  • 1 <= grid[i][j] <= 106 or grid[i][j] == -1

Approach Overview

Problem Overview: You are given a matrix where each cell contains a value or -1 (blocked). Cells connect in four directions. The remoteness of a cell equals the sum of values of all cells that are not reachable from it. The task is to compute the total remoteness across all non-blocked cells.

Approach 1: Brute Force BFS/DFS from Every Cell (O((m*n)^2) time, O(m*n) space)

Start a traversal from each non-blocked cell and mark all reachable cells using breadth-first search or depth-first search. While exploring, accumulate the sum of values in that reachable region. The remoteness for the starting cell equals totalGridSum - reachableSum. Repeat for every cell and accumulate the results. This approach is straightforward but inefficient because the same connected region gets recomputed many times.

Approach 2: Connected Components with DFS (O(m*n) time, O(m*n) space)

The key observation: every cell in the same connected component can reach the exact same set of cells. Their remoteness values therefore depend only on the component's total value. First compute the sum of all non-blocked cells in the grid. Then scan the matrix and run DFS from each unvisited valid cell to discover its connected component. During DFS, count the number of cells and accumulate their value sum. If a component has sum S and size K, each cell's remoteness equals totalSum - S. The total contribution from this component becomes K * (totalSum - S). This eliminates repeated traversal and processes each cell exactly once.

Approach 3: Union Find Components (O(m*n * α(m*n)) time, O(m*n) space)

You can also treat the grid as a graph and build connected components using Union Find. Iterate through the matrix, union adjacent non-blocked cells, and maintain the sum of values for each root component. After building the structure, compute remoteness for each component using the same formula componentSize * (totalSum - componentSum). Union Find works well if connectivity queries are reused or extended later, but the DFS approach is simpler for this problem.

Recommended for interviews: The DFS connected component strategy is what most interviewers expect. It shows you recognize that all cells in a component share identical reachable sets, reducing redundant traversals. Brute force demonstrates the baseline idea, but collapsing the grid into components and applying the formula K * (totalSum - S) shows strong graph reasoning and optimization skills.

Solution

First, we count the number of non-blocking cells in the matrix, denoted as cnt. Then, starting from each non-blocking cell, we use DFS to calculate the sum s of the cells in each connected block and the number of cells t. Then, all (cnt - t) cells in other connected blocks can be added with s. We sum up the results of all connected blocks.

The time complexity is O(n^2), and the space complexity is O(n^2). Here, n is the side length of the matrix.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
BFS/DFS from Every CellO((m*n)^2)O(m*n)Conceptual baseline or very small grids
DFS Connected ComponentsO(m*n)O(m*n)Best general solution; simple and optimal for grid traversal
Union Find ComponentsO(m*n * α(m*n))O(m*n)Useful when connectivity structures must support future queries

Video Solution

2852. Sum of Remoteness of All Cells - Week 4/5 Leetcode January Challenge • Programming Live with Larry • 229 views views

Watch 3 more video solutions →

Frequently Asked Questions

Is Sum of Remoteness of All Cells easy or hard?
The problem is typically classified as Medium. The challenge is recognizing that remoteness depends on connected components rather than individual cells, allowing the solution to be optimized from repeated traversals to a single O(m*n) pass.
Sum of Remoteness of All Cells Python/Java solution
Most implementations use DFS on the grid. Traverse neighbors in four directions, accumulate the component sum and size, then apply the formula componentSize * (totalSum - componentSum). The same logic translates directly to Python, Java, C++, Go, or TypeScript.
How to solve Sum of Remoteness of All Cells in O(n)?
Treat the grid as a graph and compute connected components. First calculate the sum of all non-blocked cells. Run DFS to determine the size and value sum of each component. For a component with sum S and size K, add K * (totalSum - S) to the answer. This visits every cell once, giving O(m*n) time.
What is the best approach for Sum of Remoteness of All Cells?
The optimal approach groups cells into connected components using DFS. Compute the total sum of all valid cells in the grid, then for each component calculate its sum and size. Each cell contributes totalSum minus componentSum to the remoteness, so the component contributes size * (totalSum - componentSum). This processes the grid in O(m*n) time.
Is Sum of Remoteness of All Cells asked at Google/Amazon/Meta?
Grid traversal and connected component problems frequently appear in interviews at companies like Amazon, Google, and Meta. Variants involving DFS, BFS, or Union Find on matrices are common because they test graph modeling and optimization skills.
What data structure is used in Sum of Remoteness of All Cells?
The primary data structures are a grid traversal stack or recursion for DFS, a visited matrix to avoid revisiting cells, and optionally a Union Find structure to track connected components. These help group reachable cells efficiently.
What is the time complexity of Sum of Remoteness of All Cells?
Using the DFS connected component method, the time complexity is O(m*n) because each cell in the grid is visited once. The space complexity is also O(m*n) due to the visited structure and recursion stack or explicit stack.

Ready to solve this problem?

Practice Sum of Remoteness of All Cells with our built-in code editor and test cases.

Practice on FleetCode