Sum of Remoteness of All Cells - Problem
You're given an n ร n grid where each cell contains either a positive integer or -1 (representing a blocked cell). Your task is to calculate the "remoteness" of every cell and return their sum.
What is Remoteness?
For any non-blocked cell (i, j), its remoteness R[i][j] is the sum of all values in cells that are unreachable from (i, j) through valid moves. You can only move between adjacent non-blocked cells (up, down, left, right).
For blocked cells, R[i][j] = 0.
Goal: Return the sum of remoteness values for all cells in the grid.
Think of it like islands in an ocean - cells on different islands can't reach each other, so they contribute to each other's remoteness!
Input & Output
example_1.py โ Basic 3x3 Grid
$
Input:
grid = [[1, -1, 3], [5, 6, -1], [-1, 2, 4]]
โบ
Output:
32
๐ก Note:
Component 1: {1} with sum=1, remoteness=14 each. Component 2: {5,6} with sum=11, remoteness=4 each. Component 3: {3} with sum=3, remoteness=12 each. Component 4: {2,4} with sum=6, remoteness=9 each. Total: 1ร14 + 2ร4 + 1ร12 + 2ร9 = 32
example_2.py โ All Connected
$
Input:
grid = [[1, 2], [3, 4]]
โบ
Output:
0
๐ก Note:
All cells are connected in one component. Each cell can reach all others, so remoteness is 0 for each cell. Total sum = 0.
example_3.py โ Single Cell
$
Input:
grid = [[5]]
โบ
Output:
0
๐ก Note:
Only one cell exists. It has no unreachable cells, so remoteness = 0. Total sum = 0.
Constraints
- 1 โค n โค 1000
- grid[i][j] is either -1 or in the range [1, 106]
- There is at least one non-blocked cell in the grid
Visualization
Tap to expand
Understanding the Visualization
1
Map the Islands
Identify separate landmasses (connected components) using Union-Find or BFS
2
Calculate Island Populations
Sum up the population (cell values) for each island
3
Compute Remoteness
For each community, remoteness = populations of all other islands
4
Sum All Remoteness Values
Add up remoteness values from all communities across all islands
Key Takeaway
๐ฏ Key Insight: Group cells into connected components first, then use mathematical relationships to avoid redundant traversals - this transforms an O(nโด) problem into O(nยฒ)!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code