Parcel-delivery app~40 min2s · 256 MBtarget O(n!) worst case, far fewer with pruning time, O(n) spaceclassic twin: lc-51backtracking
A warehouse has a square floor of n by n cells. Some cells hold a pillar, and a robot cannot stand on a pillar. The planner wants to station n scanning robots, one in every row and one in every column.
Two robots must not see each other. They see each other along a row, along a column, and along a diagonal in either direction. A pillar does not block the view. The planner wants to know how many different layouts are valid.
Write count_layouts(floor).
floor is a square grid. floor[r][c] is 1 for a pillar and 0 for a free cell.Input: floor = [[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]]
Output: 2The solution fills the rows from the top. It abandons a partial layout as soon as a robot would be seen. The table counts the partial layouts that survive after each row.
| Rows filled | Valid partial layouts |
|---|---|
| 1 | 4 |
| 2 | 6 |
| 3 | 4 |
| 4 | 2 |
Two complete layouts remain. They have the robots in the columns 1, 3, 0, 2 and in the columns 2, 0, 3, 1, counting columns from 0.
Input: floor = [[0]]
Output: 1One robot on a one-cell floor is a valid layout.
Input: floor = [[0,1,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]]
Output: 1A pillar in the first row at column 1 removes the layout with the robots in the columns 1, 3, 0, 2. The other layout stays.
1 ≤ n ≤ 11, where floor has n rows and n columnsTrying every way to put one robot in each row and column costs n! layouts, which is about 4 × 10^7 for n = 11. Each one needs a check. Placing the rows one at a time and stopping at the first conflict visits far fewer layouts: 166,926 calls for an empty floor with n = 11.