Approach
Depth-first search
For Sum of Remoteness of All Cells, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 49 lines of Java from the credited upstream file 2852.java.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public long sumRemoteness(int[][] grid) {3 long ans = 0;4 long sum = 0;5 6 for (int[] row : grid)7 for (int cell : row)8 sum += Math.max(0, cell);9 10 for (int i = 0; i < grid.length; ++i)11 for (int j = 0; j < grid[0].length; ++j)12 if (grid[i][j] > 0) {13 long[] res = dfs(grid, i, j);14 final long count = res[0];15 final long componentSum = res[1];16 ans += (sum - componentSum) * count;17 }18 19 return ans;20 }21 22 private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};23 24 25 26 private long[] dfs(int[][] grid, int i, int j) {27 if (i < 0 || i == grid.length || j < 0 || j == grid[0].length)28 return new long[] {0, 0};29 if (grid[i][j] == -1)30 return new long[] {0, 0};31 32 long count = 1;33 long componentSum = grid[i][j];34 grid[i][j] = -1; 35 36 for (int[] dir : DIRS) {37 final int x = i + dir[0];38 final int y = j + dir[1];39 long[] nextRes = dfs(grid, x, y);40 final long nextCount = nextRes[0];41 final long nextComponentSum = nextRes[1];42 count += nextCount;43 componentSum += nextComponentSum;44 }45 46 return new long[] {count, componentSum};47 }48}49