Online store~25 min2s · 256 MBtarget O(r c) time, O(r c) spaceclassic twin: lc-200dfs
A shop stores small goods on a rotating carousel. The carousel is a grid of bays: each row is a shelf level, and each column is a position around the carousel. A bay is empty (0) or holds stock (1).
The carousel turns, so the last column sits next to the first column on every level. The top and bottom levels are not joined. A block is a group of bays with stock that touch by a side, with the wrap-around counted.
Write count_stock_blocks(bays).
bays[r][c] is 1 when the bay holds stock.Input: bays = [[1,0,0,0,0,1],[0,0,1,1,0,0],[1,0,0,0,0,1],[0,1,0,0,1,0]]
Output: 5A scan visits the bays row by row. A bay with stock that no earlier walk reached starts a block, and a walk collects the whole block.
| Block | Start bay | Bays in the block |
|---|---|---|
| 1 | (0,0) | (0,0), (0,5) joined by the wrap |
| 2 | (1,2) | (1,2), (1,3) |
| 3 | (2,0) | (2,0), (2,5) joined by the wrap |
| 4 | (3,1) | (3,1) |
| 5 | (3,4) | (3,4) |
Without the wrap there would be 7 blocks. The answer is 5.
Input: bays = [[1,1,1]]
Output: 1One level of three bays, all with stock: one block.
Input: bays = [[1,0,1]]
Output: 1The first and last bays touch through the wrap, so they form one block.
1 ≤ rows, columns ≤ 500bays is 0 or 1A carousel has up to 500 × 500 = 250,000 bays. Merging labels between neighbours again and again can need a round for every turn of a winding block, so hundreds of millions of steps. One scan with a walk that visits each bay once costs O(r c), about 1,000,000 neighbour checks. A single block can hold all 250,000 bays, so the walk should use a stack, not recursion.