Monitoring~25 min2s · 256 MBtarget O(r c) time, O(r c) spaceclassic twin: lc-130dfs
A data hall is a grid of floor cells. A cell is open (0) or blocked by a rack or a wall (1). Every open cell holds a wireless sensor.
Gateways sit on the outer edge: every open cell in the first or last row, or in the first or last column, is a gateway. A sensor's signal passes from an open cell to any of the eight cells around it that is open, diagonals included. A sensor is cut off when its signal cannot reach any gateway.
Write count_cut_off_cells(hall).
hall[r][c] is 0 for an open cell and 1 for a blocked cell.Input: hall = [[1,1,1,1,0,0,0],[1,0,0,0,1,1,1],[1,1,1,1,1,0,1],[1,0,1,1,0,1,1],[1,1,1,1,1,1,1]]
Output: 3A search starts from every open cell on the outer edge at once, and spreads through open cells in eight directions. The open cells not reached are cut off.
| Open cells | Reached from the edge? | Why |
|---|---|---|
| (0,4), (0,5), (0,6) | yes | they are gateways |
| (1,1), (1,2), (1,3) | yes | (1,3) touches the gateway (0,4) at a corner |
| (2,5) | no | all its neighbours are blocked, except the corner (3,4) |
| (3,4) | no | it touches only (2,5) at a corner |
| (3,1) | no | every cell around it is blocked |
Three sensors are cut off: (2,5), (3,4) and (3,1). With sides only, the corner contact at (1,3) would not count, and 6 sensors would be cut off.
Input: hall = [[1,1,1],[1,0,1],[1,1,1]]
Output: 1The one open cell is in the middle, with a wall all round it.
Input: hall = [[0]]
Output: 0The only cell is on the outer edge, so it is a gateway.
1 ≤ rows, columns ≤ 500hall is 0 or 1A hall has up to 500 × 500 = 250,000 cells. Searching outwards from every open cell to look for the edge can cost 250,000 steps per cell, so about 6 × 10^10 steps. One search that starts at the gateways and spreads inwards visits each cell once, so it costs O(r c), about 2,000,000 neighbour checks.