Engineering platform~20 min2s · 256 MBtarget O(rows * cols) time, O(rows * cols) spacetraversal
You work on the platform behind a build system. A farm of build machines runs jobs in hourly slots, and the timetable repeats every day.
The scheduler keeps a grid. Each row is a machine and each column is an hour of the day. A cell is 1 when that slot is free, and 0 when a job runs.
Free time is only useful in one piece. Your team lead asks: "How many separate blocks of free slots do we have?" The last hour of the day is followed by the first hour of the next day, so a block can wrap past midnight.
Write count_free_blocks(slots).
slots[r][c] is 1 for a free slot of machine r in hour c, and 0 for a busy one. All rows have the same length.Input: slots = [[1, 0, 0, 1], [0, 0, 1, 1], [1, 0, 0, 0]]
Output: 2| Scan reaches | State | Block | Slots marked |
|---|---|---|---|
| row 0, hour 0 | free, not marked | 1 | (0,0), then (0,3) through the wrap, then (1,3), then (1,2) |
| (0,3), (1,2), (1,3) | already marked | 1 | none |
| row 2, hour 0 | free, not marked | 2 | (2,0) only: its wrapped neighbour (2,3) is busy |
Without the wrap the first block would split in two, and the answer would be 3.
Input: slots = [[1, 0, 1], [0, 0, 0], [1, 0, 1]]
Output: 2In a day of 3 hours, hour 2 wraps to hour 0. So the two free slots of the top machine are one block, and so are the two of the bottom machine.
Input: slots = [[1], [0], [1]]
Output: 2With one hour a day, the wrap joins a slot to itself and changes nothing.
1 ≤ slots.length ≤ 500 (machines)1 ≤ slots[r].length ≤ 500 (hours in a day, the same for every machine)slots[r][c] is 0 or 1There are 250,000 slots, and a block can wind through all of them. Each visit must cost a few steps.
Counting how many slots are in each block by comparing every pair of slots would need billions of steps. Marking each slot once and walking to its four neighbours needs about 1,000,000 checks.