0% found this document useful (0 votes)
5 views

Ai 4

The document contains a Python program that solves the N-Queens problem using backtracking. It defines functions to check if a queen can be placed safely on a square, recursively place queens on the board, and the main function to take input and print the solution.

Uploaded by

rp7938008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Ai 4

The document contains a Python program that solves the N-Queens problem using backtracking. It defines functions to check if a queen can be placed safely on a square, recursively place queens on the board, and the main function to take input and print the solution.

Uploaded by

rp7938008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

INPUT:

def issafe(arr,x,y,n):
for row in range(x):
if arr[row][y] ==1:
return False
row = x
col = y
while row>=0 and col>=0:
if arr[row][col]==1:
return False
row-=1
col-=1
row = x
col = y
while row>=0 and col<n:
if arr[row][col]==1:
return False
row-=1
col+=1
return True
def nQueen(arr,x,n):
if x>=n:
return True
for col in range(n):
if issafe(arr,x,col,n):
arr[x][col]=1
if nQueen(arr,x+1,n):
return True
arr[x][col] = 0
return False
def main():
n = int(input("Enter number of Queens : "))
arr = [[0]*n for i in range(n)]
if nQueen(arr,0,n):
for i in range(n):
for j in range(n):
print(arr[i][j],end=" ")
print(
if __name__ == '__main__':
main()

OUTPUT:
Enter number of Queens : 8
10000000
00001000
00000001
00000100
00100000
00000010
01000000
00010000

You might also like