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.

Input & Output

Example 1 — Basic Grid
$ Input: grid = [[1,2,3],[4,-1,5]]
Output: 45
💡 Note: Cell (0,0) can reach (1,0), so remoteness = 2+3+5 = 10. Cell (0,1) can only reach itself, so remoteness = 1+4+3+5 = 13. Similarly for other cells, total = 45.
Example 2 — All Connected
$ Input: grid = [[1,2],[3,4]]
Output: 0
💡 Note: All cells are connected to each other, so each cell can reach all others. Remoteness of each cell is 0.
Example 3 — All Blocked Except One
$ Input: grid = [[5,-1],[-1,-1]]
Output: 0
💡 Note: Only one non-blocked cell exists. It cannot reach any other non-blocked cells (there are none), so remoteness = 0.

Constraints

  • 1 ≤ n ≤ 100
  • grid[i][j] == -1 or 1 ≤ grid[i][j] ≤ 106

Visualization

Tap to expand
Sum of Remoteness: Connected Components ProblemInput Grid1234-15Connected Components14235Sum=5Sum=2Sum=8Remoteness CalculationTotal sum = 5 + 2 + 8 = 15Cell 1: 15 - 5 = 10Cell 4: 15 - 5 = 10Cell 2: 15 - 2 = 13Cell 3: 15 - 8 = 7Cell 5: 15 - 8 = 7Total: 10+10+13+7+7 = 47🎯 Key Insight: Cells in different components contribute to each other's remoteness
Understanding the Visualization
1
Input Grid
Matrix with values and blocked cells (-1)
2
Find Components
Group connected non-blocked cells
3
Calculate Remoteness
For each cell: sum of unreachable cells
Key Takeaway
🎯 Key Insight: Group cells into connected components first, then calculate remoteness efficiently using component sums
Asked in
Google 25 Meta 18 Amazon 15
12.5K Views
Medium Frequency
~35 min Avg. Time
489 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