Problem Description
Given an n x n grid where each cell is either a positive integer or -1 (representing a blocked cell), we need to compute the sum of remoteness R[i][j] for every cell. For a non-blocked cell (i, j), R[i][j] is defined as the sum of values of all other non-blocked cells that cannot reach (i, j) using moves to adjacent non-blocked cells (up, down, left, right). Blocked cells have R[i][j] equal to 0.
Key Insights
- The problem reduces to finding connected components among non-blocked cells.
- Cells belonging to the same connected component can reach each other, while cells in different components cannot.
- Let S be the total sum of values of all non-blocked cells.
- For each component, if its aggregate sum is S_comp and the number of cells in that component is count, then each cell in that component has a remoteness of S - S_comp.
- The overall answer is obtained by summing (S - S_comp) for each non-blocked cell, which equals count * (S - S_comp) for each component.
Space and Time Complexity
Time Complexity: O(n^2) – We traverse all cells in the grid once and perform a DFS/BFS for each component. Space Complexity: O(n^2) – In worst-case scenarios, the recursion/queue used for DFS/BFS and extra storage for visitation will use space proportional to the number of cells.
Solution
We use a graph connectivity approach with either DFS or BFS to find connected components among non-blocked cells:
- First, compute the total sum S of all non-blocked cells.
- Use a DFS (or BFS) to traverse each connected component. For each component, calculate its sum (S_comp) and number of cells (count).
- For every cell in that component, the contribution to the final answer is (S - S_comp). Thus, add count * (S - S_comp) to the answer.
- Blocked cells are skipped throughout the process and contribute 0.
This method allows us to avoid repeated searches from every cell by consolidating connected component properties.