703. Sum of Remoteness of All Cells
An order n * n 0-indexed matrix grid is presented to you. The values grid[i][j] for each cell in this matrix are either positive integers or -1, which denotes a blocked cell.
Any non-blocked cell with an edge can be reached by moving from one non-blocked cell to another.
The remoteness of any cell (i, j) is represented by R[i][j], which has the following definition:
- 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.
Example 1:
Input : grid = [ [5, -1], [-1, 2] ]
Output : 7
Explanation :
Let's calculate R[0][0] . We should sum up the value of cells that can't be reached by the cell (0, 0) expect the blocked cells. So R[0][0] = 2.
Let's calculate R[1][1] . We should sum up the value of cells that can't be reached by the cell (1, 1) expect the blocked cells. So R[1][1] = 5.
The blocked cells R[0][1], R[1][0] value is equal to 0.
So the answer would be the sum of all the R[i][j] cells. That is: 2 + 0 + 0 + 5 = 7.
Example 2:
Input : grid = [[-1,1,-1],[5,-1,4],[-1,3,-1]]
Output : 39
Explanation :
Let's calculate R[0][1]. We should sum up the value of cells that can't be reached by the cell (0, 1). So R[0][1] = 5 + 4 + 3 = 12.
Now calculate R[1][2]. We should sum up the value of cells that can't be reached by the cell (1, 2). So R[1][2] = 1 + 5 + 3 = 9.
R[1][0] = 1 + 3 + 4.
R[2][1] = 1 + 5 + 4.
The blocked cells value is 0.
So the answer would be the sum of all the R[i][j] cells. That is: 0 + 12 + 0 + 8 + 0 + 9 + 0 + 10 + 0 = 39.
Now Your Turn!
Pick the correct output for the given inputInput : grid = [ [1, 2, 3], [-1, -1, -1], [4, 5, 6] ]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= n <= 300
- 1 <= grid[i][j] <= 106 or grid[i][j] == -1