Loading content...
You are tasked with arranging n thrones on an n × n grand ceremonial hall grid. Each throne represents a powerful ruler, and according to ancient kingdom protocols, no two rulers may be able to see each other directly—whether across a row, down a column, or along any diagonal line.
Your goal is to find all distinct valid arrangements of the n thrones on the grid such that no two thrones threaten each other's line of sight.
Each valid arrangement should be represented as an array of n strings, where each string has exactly n characters. In these strings:
Return all possible valid throne configurations. The solutions may be returned in any order.
A throne placed at position (row, col) can "see" (and thus conflicts with) any other throne that lies:
This means for a valid arrangement, when you place a throne in a particular cell, you must ensure no other throne shares its row, column, or any of its two diagonals.
This is a classic constraint satisfaction problem that is elegantly solved using backtracking. The approach involves:
The key optimization involves efficiently tracking which columns and diagonals are already "attacked" using sets or boolean arrays, reducing the conflict-checking time from O(n) to O(1).
n = 4[[".T..","...T","T...","..T."],["..T.","T...","...T",".T.."]]For a 4×4 grid, there are exactly two distinct ways to arrange 4 thrones such that no two can see each other. In the first arrangement, thrones are placed at positions (0,1), (1,3), (2,0), and (3,2). In the second arrangement, thrones are at (0,2), (1,0), (2,3), and (3,1). Each arrangement ensures no two thrones share a row, column, or diagonal.
n = 1[["T"]]With only a 1×1 grid, there is exactly one position to place the single throne. Trivially, there are no conflicts since there's only one throne.
n = 5[["....T","..T..","T....","...T.",".T..."],["....T",".T...","...T.","T....","..T.."],["...T.",".T...","....T","..T..","T...."],["...T.","T....","..T..","....T",".T..."],["..T..","....T",".T...","...T.","T...."],["..T..","T....","...T.",".T...","....T"],[".T...","....T","..T..","T....","...T."],[".T...","...T.","T....","..T..","....T"],["T....","...T.",".T...","....T","..T.."],["T....","..T..","....T",".T...","...T."]]For a 5×5 grid, there are exactly 10 distinct valid arrangements. Each configuration places 5 thrones such that no two share a row, column, or diagonal. The number of solutions grows non-linearly with n.
Constraints