Ctrl K

Total of the Unreachable

Medium
You are given a square n × n table grid. A cell holding -1 is a wall; every other cell is open and holds a positive number. From an open cell you can step to any open cell that shares a side with it. For every open cell, add up the values of all open cells it cannot reach. Walls contribute nothing. Return the grand total over all cells of the table.
Example 1
grid=[[2, -1], [-1, 5]] → 7

The cells 2 and 5 are cut off by walls. Cell 2 cannot reach 5 and cell 5 cannot reach 2: 5 + 2 = 7.

Example 2
grid=[[1, 4, -1], [-1, -1, -1], [6, -1, 3]] → 37

There are three regions: {1, 4}, {6} and {3}. Cells 1 and 4 each miss 6 + 3 = 9, cell 6 misses 1 + 4 + 3 = 8, cell 3 misses 1 + 4 + 6 = 11. In total 9 + 9 + 8 + 11 = 37.

Example 3
grid=[[7, 7], [7, -1]] → 0

All open cells are connected, so nothing is out of reach.

Constraints
  • 1 ≤ n ≤ 300
  • grid[i][j] = -1 or 1 ≤ grid[i][j] ≤ 10⁶
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsA Board Cut by Slashes MediumDrain the Landlocked Ponds MediumLand Regions on a Map MediumLargest Forest Patch MediumMerge Contact Cards Medium
loading Python…
Input
grid=[[2, -1], [-1, 5]]
Expected
7

Run checks the first 3 tests in your browser. Submit checks all 99 tests on the server, hidden ones included.