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: 35
💡 Note: Two components: {1,4} with sum 5 and {2,3,5} with sum 10. Cell (0,0): remoteness = 10, Cell (0,1): remoteness = 5, Cell (0,2): remoteness = 5, Cell (1,0): remoteness = 10, Cell (1,2): remoteness = 5. Total = 35.
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 of All Cells INPUT n x n Grid Matrix 1 2 3 4 -1 5 Non-blocked cell Blocked cell (-1) Input Values grid = [[1,2,3], [4,-1,5]] n = 2, m = 3 ALGORITHM STEPS 1 Find Components Use BFS/DFS to find connected components 2 Calculate Sums Sum values in each component separately 3 Count Cells Count non-blocked cells in each component 4 Compute Remoteness R = totalSum - compSum for each cell Components Found: Comp 1: {1,2,3,4} Sum=10, Count=4 Comp 2: {5} Sum=5, Count=1 Total Sum = 15 FINAL RESULT Remoteness for each cell: Cell (0,0): R = 15-10 = 5 Cell (0,1): R = 15-10 = 5 Cell (0,2): R = 15-10 = 5 Cell (1,0): R = 15-10 = 5 Cell (1,1): R = 0 (blocked) Cell (1,2): R = 15-5 = 10 Comp1 cells: 4 x 5 = 20 Comp2 cells: 1 x 10 = 10 Formula: count x otherSum Output 45 Sum of all R[i][j] = 45 5+5+5+5+0+10+(4x5)=45 Key Insight: For each component, the remoteness of a cell equals the sum of values in OTHER components. Instead of calculating R for each cell, multiply: count_of_cells x sum_of_other_components. Time Complexity: O(n*m) using BFS/DFS. Space Complexity: O(n*m) for visited array. TutorialsPoint - Sum of Remoteness of All Cells | Optimal Solution
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