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:
(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).R[i][j] == 0.Return the sum of R[i][j] over all cells.
Example 1:

Input: grid = [[-1,1,-1],[5,-1,4],[-1,3,-1]] Output: 39 Explanation: In the picture above, there are four grids. The top-left grid contains the initial values in the grid. Blocked cells are colored black, and other cells get their values as it is in the input. In the top-right grid, you can see the value of R[i][j] for all cells. So the answer would be the sum of them. That is: 0 + 12 + 0 + 8 + 0 + 9 + 0 + 10 + 0 = 39. Let's jump on the bottom-left grid in the above picture and calculate R[0][1] (the target cell is colored green). We should sum up the value of cells that can't be reached by the cell (0, 1). These cells are colored yellow in this grid. So R[0][1] = 5 + 4 + 3 = 12. Now let's jump on the bottom-right grid in the above picture and calculate R[1][2] (the target cell is colored green). We should sum up the value of cells that can't be reached by the cell (1, 2). These cells are colored yellow in this grid. So R[1][2] = 1 + 5 + 3 = 9.

Example 2:
Input: grid = [[-1,3,4],[-1,-1,-1],[3,-1,-1]] Output: 13 Explanation: In the picture above, there are four grids. The top-left grid contains the initial values in the grid. Blocked cells are colored black, and other cells get their values as it is in the input. In the top-right grid, you can see the value of R[i][j] for all cells. So the answer would be the sum of them. That is: 3 + 3 + 0 + 0 + 0 + 0 + 7 + 0 + 0 = 13. Let's jump on the bottom-left grid in the above picture and calculate R[0][2] (the target cell is colored green). We should sum up the value of cells that can't be reached by the cell (0, 2). This cell is colored yellow in this grid. So R[0][2] = 3. Now let's jump on the bottom-right grid in the above picture and calculate R[2][0] (the target cell is colored green). We should sum up the value of cells that can't be reached by the cell (2, 0). These cells are colored yellow in this grid. So R[2][0] = 3 + 4 = 7.
Example 3:
Input: grid = [[1]] Output: 0 Explanation: Since there are no other cells than (0, 0), R[0][0] is equal to 0. So the sum of R[i][j] over all cells would be 0.
Constraints:
1 <= n <= 3001 <= grid[i][j] <= 106 or grid[i][j] == -1When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine looking at a grid of numbers where some spaces are blocked and some are open, forming connected regions of open spaces. The brute force approach looks at every single open space, figures out which other spaces it can reach, adds up their numbers, and compares that to the sum of all numbers in the entire grid.
Here's how the algorithm would work step-by-step:
def sumOfRemoteness(grid):
row_count = len(grid)
col_count = len(grid[0])
total_grid_sum = 0
for row_index in range(row_count):
for col_index in range(col_count):
if grid[row_index][col_index] != -1:
total_grid_sum += grid[row_index][col_index]
# We calculate the global sum first to easily derive remoteness by subtracting component sums later
visited_cells = [[False for _ in range(col_count)] for _ in range(row_count)]
grand_total_remoteness = 0
for row_index in range(row_count):
for col_index in range(col_count):
if grid[row_index][col_index] != -1 and not visited_cells[row_index][col_index]:
component_cells = []
component_sum = 0
exploration_queue = [(row_index, col_index)]
visited_cells[row_index][col_index] = True
queue_head = 0
while queue_head < len(exploration_queue):
current_row, current_col = exploration_queue[queue_head]
queue_head += 1
component_cells.append((current_row, current_col))
component_sum += grid[current_row][current_col]
row_offsets = [-1, 1, 0, 0]
col_offsets = [0, 0, -1, 1]
for direction_index in range(4):
neighbor_row = current_row + row_offsets[direction_index]
neighbor_col = current_col + col_offsets[direction_index]
if 0 <= neighbor_row < row_count and 0 <= neighbor_col < col_count:
if grid[neighbor_row][neighbor_col] != -1 and not visited_cells[neighbor_row][neighbor_col]:
visited_cells[neighbor_row][neighbor_col] = True
exploration_queue.append((neighbor_row, neighbor_col))
# BFS traversal ensures we accurately group all connected open cells into a single component
for cell_row, cell_col in component_cells:
cell_remoteness = total_grid_sum - component_sum
grand_total_remoteness += cell_remoteness
# Accumulating individual cell remoteness values yields the final expected grand total
return grand_total_remoteness
The problem asks for the total remoteness across all non-blocked cells in a grid. For any cell, its remoteness equals the sum of values of all non-blocked cells unreachable from it. Since reachability defines connected components of adjacent non-blocked cells, each cell in a component cannot reach any non-blocked cell outside of its component.
Here's how the algorithm would work step-by-step:
def sum_remoteness(grid):
# Calculate the total sum of all non-blocked cells in the grid.
total_sum = sum(val for row in grid for val in row if val != -1)
grid_size = len(grid)
visited = [[False] * grid_size for _ in range(grid_size)]
total_remoteness = 0
# Traverse the grid to identify all connected components.
for start_row in range(grid_size):
for start_col in range(grid_size):
if grid[start_row][start_col] != -1 and not visited[start_row][start_col]:
component_sum = 0
component_count = 0
queue = [(start_row, start_col)]
visited[start_row][start_col] = True
# Explore the entire connected component using breadth-first search.
for curr_row, curr_col in queue:
component_sum += grid[curr_row][curr_col]
component_count += 1
for delta_row, delta_col in ((-1, 0), (1, 0), (0, -1), (0, 1)):
next_row = curr_row + delta_row
next_col = curr_col + delta_col
if 0 <= next_row < grid_size and 0 <= next_col < grid_size:
if grid[next_row][next_col] != -1 and not visited[next_row][next_col]:
visited[next_row][next_col] = True
queue.append((next_row, next_col))
# Accumulate the remoteness contribution for all cells in this component.
unreachable_sum = total_sum - component_sum
total_remoteness += unreachable_sum * component_count
return total_remoteness
| Case | How to Handle |
|---|---|
| Grid is completely empty or null | Return zero immediately since there are no non-zero cells to process. |
| Grid contains only zeros with no non-zero cells | Return zero as the iteration finds no valid connected components. |
| A single non-zero cell isolated entirely by zeros | Treat that single cell as its own component where component sum equals the cell value itself. |
| The entire grid consists of a single connected component of non-zero values | The remoteness for every cell will be zero since the component sum equals the total sum of all values. |
| Large grid with maximum constraints causing deep recursion in DFS | Use an iterative breadth-first search or iterative depth-first search to avoid stack overflow errors. |
| Extremely large grid sizes causing integer overflow from large sum totals | Use 64-bit integer types for tracking both component sums and total grid sums. |
| Grid values are negative numbers | Ensure the component traversal correctly treats non-zero numbers as valid component cells regardless of sign. |