Skip to content

ORIGINAL CODING QUESTION

Guards on a partly blocked floor

An n by n office floor plan marks each desk as usable (0) or blocked (1). Place exactly n security guards on usable desks so that no two guards share a row, a column or either diagonal direction. Blocked desks cannot hold a guard but do not interrupt a line of sight. Count the valid placements.

Open practice workspace

Original exercise · hard. Editorial role relevance does not imply a company has asked this question.

Input and output

n, then n*n desk flags row by row (0 = usable, 1 = blocked). Print the number of placements.

Constraints

1 ≤ n ≤ 8; every flag is 0 or 1.

Example 1

Input

4
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

Output

2

An open 4 by 4 floor has two placements.

Example 2

Input

4
0 1 0 0
0 0 0 0
0 0 0 0
0 0 0 0

Output

1

Blocking row 0, column 1 removes the placement that needed it, leaving one.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

Exactly one guard goes in each row, so decide rows one at a time.

Hint 2

Track used columns and both diagonal families; cells on one diagonal share row - col or row + col.

Hint 3

Skip blocked desks and occupied lines, recurse to the next row, then remove the guard before trying the next column.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →