Sum of Remoteness of All Cells - Problem
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 valuesgrid[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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code