Remoteness in Linear Time

Approach here could be using either a queue or stack, but basically for each cell, traverse the connected nodes, calculate the sum of the connected notes. To avoid a second pass, use a proxy hash table. At the same time calculate the total sum of the grid. Do another linear pass at the end to calculate the remoteness since you have all the data that you need pre-calculated and stored in the hash tables. Code is down below, cheers, ACC.

Sum of Remoteness of All Cells - LeetCode

2852. Sum of Remoteness of All Cells
Medium

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:

  • 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 = [[-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 <= 300
  • 1 <= grid[i][j] <= 106 or grid[i][j] == -1

public long SumRemoteness(int[][] grid)
{
 long totalSum = 0;
 Hashtable cellToSumIndex = new Hashtable();
 Hashtable indexToSum = new Hashtable();
 int index = 0;
 for (int r = 0; r < grid.Length; r++)
 for (int c = 0; c < grid[r].Length; c++)
 totalSum += SetConnectedSum(grid, r, c, cellToSumIndex, indexToSum, index++);
 long retVal = 0;
 for (int r = 0; r < grid.Length; r++)
 for (int c = 0; c < grid[r].Length; c++)
 {
 ConnectedCell cc = new ConnectedCell(r, c);
 if (cellToSumIndex.ContainsKey(cc.key))
 retVal += (totalSum - (long)indexToSum[(int)cellToSumIndex[cc.key]]);
 }
 return retVal;
}
private long SetConnectedSum(int[][] grid,
 int row,
 int col,
 Hashtable cellToSumIndex,
 Hashtable indexToSum,
 int index)
{
 if (grid[row][col] == -1) return 0L;
 ConnectedCell cc = new ConnectedCell(row, col);
 if (cellToSumIndex.ContainsKey(cc.key)) return 0L;
 long sum = 0;
 Stack stack = new Stack();
 cellToSumIndex.Add(cc.key, index);
 stack.Push(cc);
 while(stack.Count > 0)
 {
 ConnectedCell currentCell = stack.Pop();
 sum += grid[currentCell.row][currentCell.col];
 int[] rowDelta = { 1, -1, 0, 0 };
 int[] colDelta = { 0, 0, 1, -1 };
 for (int i = 0; i < rowDelta.Length; i++)
 {
 int nextRow = currentCell.row + rowDelta[i];
 int nextCol = currentCell.col + colDelta[i];
 if (nextRow >= 0 &&
 nextRow < grid.Length &&
 nextCol >= 0 &&
 nextCol < grid[nextRow].Length &&
 grid[nextRow][nextCol] != -1)
 {
 ConnectedCell nextCell = new ConnectedCell(nextRow, nextCol);
 if (!cellToSumIndex.ContainsKey(nextCell.key))
 {
 cellToSumIndex.Add(nextCell.key, index);
 stack.Push(nextCell);
 }
 }
 }
 }
 indexToSum.Add(index, sum);
 return sum;
}
public class ConnectedCell
{
 public int row = 0;
 public int col = 0;
 public int key = 0;
 public ConnectedCell(int row, int col)
 {
 this.row = row;
 this.col = col;
 this.key = row * 305 + col;
 }
}

Comments

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. 🔍 Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...