Write a python code for 8 queens problem
8 Queens problem:
The 8 queens problem is a classic problem in computer science and mathematics, which involves placing 8 chess queens on an 8x8 chessboard so that no two queens threaten each other. Here is a Python code to solve this problem using a recursive backtracking algorithm.
# function to check if a position is safe for the queen def isSafe(board, row, col, n): # check if there is a queen in the same row for i in range(col): if board[row][i] == 1: return False # check if there is a queen in the upper diagonal for i, j in zip(range(row, -1, -1), range(col, -1, -1)): if board[i][j] == 1: return False # check if there is a queen in the lower diagonal for i, j in zip(range(row, n, 1), range(col, -1, -1)): if board[i][j] == 1: return False # if all checks pass, the position is safe return True # recursive function to solve the 8 queens problem def solve(board, col, n): # if all queens are placed, return True if col >= n: return True # try placing the queen in each row of the current column for i in range(n): if isSafe(board, i, col, n): # place the queen board[i][col] = 1 # recursively solve the next column if solve(board, col+1, n): return True # if the solution is not found, remove the queen board[i][col] = 0 # if no solution is found, return False return False # main function to solve the 8 queens problem def solve8Queens(): n = 8 board = [[0]*n for i in range(n)] if solve(board, 0, n): for i in range(n): for j in range(n): print(board[i][j], end=" ") print() else: print("No solution found.")
To solve the problem, simply call the solve8Queens()
function. It will print the solution if one is found, or print "No solution found." otherwise. Note that there may be multiple solutions to the 8 queens problem, but this algorithm will only find one of them.
No comments: