OneCompiler

Q3

207

KHUSHAL GAUTAM

CS20B1080

#Function to place n pieces on the ChessBoard, starting from the first row.
def placePieces(ChessBoard, pieces, n):
if n == 0:
return True

for i in range(4):
    for j in range(4):
        if isValid(ChessBoard, i, j):
            # Place piece on the ChessBoard
            ChessBoard[i][j] = pieces[n-1]
            # Place the remaining pieces recursively
            if placePieces(ChessBoard, pieces, n-1):
                return True
            # If placing the remaining pieces was unsuccessful, remove the current piece
            ChessBoard[i][j] = 0

return False

Function to check if a position (row, col) is a valid spot for a new piece on the ChessBoard.

def isValid(ChessBoard, row, col):
# Check row and column
for i in range(4):
if ChessBoard[row][i] != 0 or ChessBoard[i][col] != 0:
return False

# Check diagonal
for i in range(4):
    for j in range(4):
        if i + j == row + col or i - j == row - col:
            if ChessBoard[i][j] != 0:
                return False
return True

Function to print the chessChessBoard.

def printChessBoard(ChessBoard):
for row in ChessBoard:
print(' ' + ' '.join(['-' if cell == 0 else cell for cell in row]) + ' ')

Initializing the Chess Board with all empty cells

ChessBoard = [[0 for x in range(4)] for y in range(4)]

Defining the pieces

pieces = ['R', 'R', 'B', 'B']

Placing the pieces recursively

placePieces(ChessBoard, pieces, len(pieces))

Printing the final Chess Board

printChessBoard(ChessBoard)