Added all the codes.

This commit is contained in:
K
2025-06-10 00:54:39 +05:30
parent 5d4de88cc9
commit a77540df2e
17 changed files with 1434 additions and 0 deletions
+61
View File
@@ -0,0 +1,61 @@
# Assignment-B4 (N-Queen)
"""
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
Problem Statement: Implement a solution for a Constraint Satisfaction Problem using Branch and Bound and Backtracking for n-queens problem or a graph coloring problem.
Code from ArtificialIntelligence (SPPU - Third Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-te-comp-content/ArtificialIntelligence
"""
# BEGINNING OF CODE
def placeQueens(i, cols, leftDiagonal, rightDiagonal, cur):
n = len(cols)
if i == n:
return True
for j in range(n):
if cols[j] or rightDiagonal[i + j] or leftDiagonal[i - j + n - 1]:
continue
cols[j] = 1
rightDiagonal[i + j] = 1
leftDiagonal[i - j + n - 1] = 1
cur.append(j)
if placeQueens(i + 1, cols, leftDiagonal, rightDiagonal, cur):
return True
cur.pop()
cols[j] = 0
rightDiagonal[i + j] = 0
leftDiagonal[i - j + n - 1] = 0
return False
def nQueen(n):
cols = [0] * n
leftDiagonal = [0] * (n * 2)
rightDiagonal = [0] * (n * 2)
cur = []
board = [['.' for _ in range(n)] for _ in range(n)]
if placeQueens(0, cols, leftDiagonal, rightDiagonal, cur):
for i in range(n):
board[i][cur[i]] = 'Q'
return board
else:
return None
def printBoard(board):
if board:
for row in board:
print(" ".join(row))
else:
print("No solution exists.")
n = int(input("Enter the number of queens:\t"))
board = nQueen(n)
printBoard(board)
# END OF CODE