Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Eight queens problem
- # we implement a backtracking algorithm to solve the problem
- # we use a two-dimensional array to represent the chessboard
- # 0 stands for an empty cell, 1 stands for a queen
- sz = 8 # size of the board
- def main():
- a = [[0 for i in range(sz)] for j in range(sz)] # 1 stands for a queen
- search(a, 0)
- def isLegal(a, k, i): # can put a queen at a[k][i]?
- # check row
- for j in range(0, sz):
- if a[k][j] == 1:
- return False
- # check column
- for j in range(0, sz):
- if a[j][i] == 1:
- return False
- # check diagonal
- for x in range(0, sz):
- for y in range(0, sz):
- if x + y == k + i and a[x][y] == 1:
- return False
- if x - y == k - i and a[x][y] == 1:
- return False
- return True
- def search(a, k): # search for a solution starting from row k in a existing chessboard a
- if k == sz: # we have found a solution
- printFormated(a)
- return
- for i in range(0, sz):
- if isLegal(a, k, i):
- a[k][i] = 1 # put a queen at a[k][i]
- search(a, k + 1) # search for a solution starting from row k + 1
- a[k][i] = 0 # remove the queen at a[k][i]
- kase = 0
- def printFormated(a):
- global kase
- kase += 1
- print("Case", kase, ":")
- for i in range(0, sz):
- for j in range(0, sz):
- if a[i][j] == 1:
- print("Q", end = " ")
- else:
- print("*", end = " ")
- print('')
- print('')
- main()
- print("Total:", kase)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement