I have written a code to solve the N-Queen problem for a 14 by 14 chessboard. There are preplaced queens (see below for the sample input and output). The lines of sample input (after the 3) represent the positions of the preplaced queens. For example, "1 1 2 9 3 6 4 10" refers to the 4 preplaced queens are at (1st row 1st column), (2nd row, 9th column), (3rd row 6th column), (4th row, 10th column).
I am hoping that it will return me the number of solutions. But when I tried running the code, I got time limit exceeded, even for the sample input.
I will try the list of tuples method, but let me know if there is a more efficient implementation. Thanks in advance
[![Question screenshot][1]][1]
Sample Input
3
1 1 2 9 3 6 4 10
1 9 12 8 8 5 2 7
2 10 10 3
Sample Output
39
32
2414
import sys
def nQueens(n, pre_placed_rows, pre_placed_cols, N, state=[], col=1):
if col > n: return [state]
res = []
for i in range(1, n+1):
if invalid(state, i): continue
for sol in nQueens(n, pre_placed_rows, pre_placed_cols, N, state + [i], col+1):
if N == 2: # 2 preplaced queens
if sol[pre_placed_cols[0]-1] == pre_placed_rows[0] and sol[pre_placed_cols[1]-1] == pre_placed_rows[1]:
res.append(sol) #[sol]
elif N == 3: # 3 preplaced queens
if sol[pre_placed_cols[0]-1] == pre_placed_rows[0] and sol[pre_placed_cols[1]-1] == pre_placed_rows[1] and sol[pre_placed_cols[2]-1] == pre_placed_rows[2]:
res.append(sol)
else: # 4 preplaced queens
if sol[pre_placed_cols[0]-1] == pre_placed_rows[0] and sol[pre_placed_cols[1]-1] == pre_placed_rows[1] and sol[pre_placed_cols[2]-1] == pre_placed_rows[2] and sol[pre_placed_cols[3]-1] == pre_placed_rows[3]:
res.append(sol)
return res
def invalid(s, r2): # is it safe to put the queen
if not s:
return False
if r2 in s:
return True
c2 = len(s) + 1
return any(abs(c1-c2) == abs(r1-r2) for c1, r1 in enumerate(s, 1))
num_case = int(sys.stdin.readline())
for _ in range(num_case):
s = sys.stdin.readline().split()
N = len(s) // 2
pre_placed_rows = []
pre_placed_cols = []
n = 14
for i in range(N):
pre_placed_rows.append(int(s[2*i]))
pre_placed_cols.append(int(s[2*i+1]))
print(len(nQueens(n, pre_placed_rows, pre_placed_cols, N)))
nQueens()
constructs all possible solutions but drops those that don't have a queen in the pre-placed squares. That's a lot of extra work.state
should start with the pre-placed queens already filed in andnQueens()
should try to fill in the rest. \$\endgroup\$ – RootTwo Nov 4 '20 at 0:26