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 C++ from the credited upstream file 2852.cpp.
- The implementation visibly relies on sequence storage.
- 3 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:3 long long sumRemoteness(vector<vector<int>>& grid) {4 const long sum = accumulate(grid.begin(), grid.end(), 0L,5 [](long acc, const vector<int>& row) {6 return acc +7 accumulate(row.begin(), row.end(), 0L,8 [](long acc, int num) { return acc + max(0, num); });9 });10 11 long ans = 0;12 13 for (int i = 0; i < grid.size(); ++i)14 for (int j = 0; j < grid[0].size(); ++j)15 if (grid[i][j] > 0) {16 const auto [count, componentSum] = dfs(grid, i, j);17 ans += (sum - componentSum) * count;18 }19 20 return ans;21 }22 23 private:24 static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};25 26 27 28 pair<int, long> dfs(vector<vector<int>>& grid, int i, int j) {29 if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size())30 return {0, 0};31 if (grid[i][j] == -1)32 return {0, 0};33 34 int count = 1;35 long componentSum = grid[i][j];36 grid[i][j] = -1; 37 38 for (const auto& [dx, dy] : kDirs) {39 const int x = i + dx;40 const int y = j + dy;41 const auto [nextCount, nextComponentSum] = dfs(grid, x, y);42 count += nextCount;43 componentSum += nextComponentSum;44 }45 46 return {count, componentSum};47 }48};49