N-Queen Problem

N-Queen Problem#

Mahmood Amintoosi, Fall 2024

Computer Science Dept, Ferdowsi University of Mashhad

%matplotlib inline
# %matplotlib notebook

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
def nqueen_bk_objfun(x):
    f = 0
    N = len(x)
    conflictIndices = []
    for i in range(N):
        if x[i] != 0:
            for j in range(i + 1, N):
                if x[j] != 0:
                    if abs(x[i] - x[j]) == abs(i - j) or x[i] == x[j]:
                        f += 1
                        conflictIndices.append([i, x[i], j, x[j]])
    return f, conflictIndices
def is_safe(x, i, j):
    for k in range(i):
        shart = x[k] == j or abs(x[k] - j) == abs(k - i)
        if shart:
            return False
    return True
def nqueen_bk(i, x):
    N = len(x)
    if i == N:
        print(x)
    else:
        for j in range(N):
            if is_safe(x, i, j):
                x[i] = j
                nqueen_bk(i + 1, x)
                # x[i] = -1
x = -np.ones(4)
nqueen_bk(0, x)
# 1302
# 2301
[1. 3. 0. 2.]
[2. 0. 3. 1.]