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
Island Communities - Remoteness Visualization324Island APopulation: 951Island BPopulation: 67Island CPopulation: 7Remoteness CalculationIsland A communities (3,2,4): Each has remoteness = 6 + 7 = 13Island B communities (5,1): Each has remoteness = 9 + 7 = 16Island C community (7): Has remoteness = 9 + 6 = 15Total: 3ร—13 + 2ร—16 + 1ร—15 = 39 + 32 + 15 = 86
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ยฒ)!
Asked in
Google 45 Amazon 38 Meta 29 Microsoft 22
21.4K Views
Medium-High Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen