Who needs 8 queens when you can have N?
Time limit1sMemory limit128 MB
Find the lexicographically smallest placement of N non-attacking queens on an N by N board for each test case.
- Level
Medium6 of 10
- Topics
- Backtracking, Recursion, Bit manipulation
- Solved
- No attempts yet
Problem
The eight queens puzzle asks you to place eight queens on an 8x8 board so that no queen attacks another. The N queens problem asks the same thing on an NxN board with N queens.
Two queens attack each other when they share a row, share a column, or sit on a common diagonal. Number the rows and the columns from . Queens at and sit on a common diagonal when or .
A valid placement holds exactly one queen in every row and exactly one in every column, so it is written as a vector in which is the column of the queen in row . That vector is a permutation of through .
Every admits more than one valid placement, so the answer is pinned to the lexicographically smallest vector. To compare two vectors, read them from index and find the first position where they differ. The vector with the smaller value at that position is the smaller one.
Input
The first line contains the number of test cases (). Each of the next lines contains one integer ().
Output
Print two lines per test case, in the order the cases are given. The first line contains . The second line contains the lexicographically smallest vector for that board, that is the column numbers separated by single spaces.