Safe Placement Puzzle - Problem

Place K non-attacking rooks on an N×N chessboard where some squares may be blocked.

Two rooks are attacking each other if they are in the same row or column and there are no blocked squares between them.

Return all valid placements as a list of coordinates, where each placement is represented as [[r1,c1], [r2,c2], ..., [rK,cK]].

The board is represented as a 2D array where 0 = empty square, 1 = blocked square.

Input & Output

Example 1 — Basic 3×3 Board
$ Input: board = [[0,1,0],[0,0,0],[1,0,0]], k = 2
Output: [[[0,0],[1,1]], [[0,0],[1,2]], [[0,0],[2,1]], [[0,2],[1,0]], [[0,2],[1,1]], [[1,0],[2,1]], [[1,1],[2,1]], [[1,2],[2,1]]]
💡 Note: Place 2 non-attacking rooks on a 3×3 board with blocked squares at (0,1) and (2,0). Multiple valid placements exist where rooks don't attack each other.
Example 2 — Small Board, One Rook
$ Input: board = [[0,0],[1,0]], k = 1
Output: [[[0,0]], [[0,1]], [[1,1]]]
💡 Note: Place 1 rook on a 2×2 board with one blocked square. Three valid positions: (0,0), (0,1), and (1,1).
Example 3 — No Valid Placement
$ Input: board = [[0,1],[1,0]], k = 2
Output: []
💡 Note: Only two valid squares (0,0) and (1,1) remain, but they're on the same diagonal. Since rooks attack along rows/columns (not diagonals), this should have a solution, but if there are blocks preventing placement, return empty array.

Constraints

  • 1 ≤ N ≤ 8
  • 1 ≤ K ≤ N
  • board[i][j] ∈ {0, 1}
  • 0 = empty square, 1 = blocked square

Visualization

Tap to expand
INPUT BOARDALGORITHM STEPSFINAL RESULT0,0X0,21,01,11,2X2,12,2Place K=2 rooksRed squares blocked1Try first rook position2Check conflicts with placed rooks3If conflict, backtrack and try next4Continue until K rooks placedBacktracking AlgorithmPrune invalid branches earlyValid Solutions Found:[[0,0],[1,1]][[0,0],[1,2]]... and 6 moreTotal: 8 solutionsAll non-attackingplacements foundKey Insight:Backtracking builds solutions incrementally, eliminating invalid branches earlyinstead of checking all combinations at the end. This dramatically reduces search space.TutorialsPoint - Safe Placement Puzzle | Backtracking Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
23.4K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen