|
| 1 | +''' |
| 2 | +
|
| 3 | + The nqueens problem is of placing N queens on a N * N |
| 4 | + chess board such that no queen can attack any other queens placed |
| 5 | + on that chess board. |
| 6 | + This means that one queen cannot have any other queen on its horizontal, vertical and |
| 7 | + diagonal lines. |
| 8 | +
|
| 9 | +''' |
| 10 | +solution = [] |
| 11 | + |
| 12 | +def isSafe(board, row, column): |
| 13 | + ''' |
| 14 | + This function returns a boolean value True if it is safe to place a queen there considering |
| 15 | + the current state of the board. |
| 16 | +
|
| 17 | + Parameters : |
| 18 | + board(2D matrix) : board |
| 19 | + row ,column : coordinates of the cell on a board |
| 20 | +
|
| 21 | + Returns : |
| 22 | + Boolean Value |
| 23 | +
|
| 24 | + ''' |
| 25 | + for i in range(len(board)): |
| 26 | + if board[row][i] == 1: |
| 27 | + return False |
| 28 | + for i in range(len(board)): |
| 29 | + if board[i][column] == 1: |
| 30 | + return False |
| 31 | + for i,j in zip(range(row,-1,-1),range(column,-1,-1)): |
| 32 | + if board[i][j] == 1: |
| 33 | + return False |
| 34 | + for i,j in zip(range(row,-1,-1),range(column,len(board))): |
| 35 | + if board[i][j] == 1: |
| 36 | + return False |
| 37 | + return True |
| 38 | + |
| 39 | +def solve(board, row): |
| 40 | + ''' |
| 41 | + It creates a state space tree and calls the safe function untill it receives a |
| 42 | + False Boolean and terminates that brach and backtracks to the next |
| 43 | + poosible solution branch. |
| 44 | + ''' |
| 45 | + if row >= len(board): |
| 46 | + ''' |
| 47 | + If the row number exceeds N we have board with a successful combination |
| 48 | + and that combination is appended to the solution list and the board is printed. |
| 49 | +
|
| 50 | + ''' |
| 51 | + solution.append(board) |
| 52 | + printboard(board) |
| 53 | + print() |
| 54 | + return |
| 55 | + for i in range(len(board)): |
| 56 | + ''' |
| 57 | + For every row it iterates through each column to check if it is feesible to place a |
| 58 | + queen there. |
| 59 | + If all the combinations for that particaular branch are successfull the board is |
| 60 | + reinitialized for the next possible combination. |
| 61 | + ''' |
| 62 | + if isSafe(board,row,i): |
| 63 | + board[row][i] = 1 |
| 64 | + solve(board,row+1) |
| 65 | + board[row][i] = 0 |
| 66 | + return False |
| 67 | + |
| 68 | +def printboard(board): |
| 69 | + ''' |
| 70 | + Prints the boards that have a successfull combination. |
| 71 | + ''' |
| 72 | + for i in range(len(board)): |
| 73 | + for j in range(len(board)): |
| 74 | + if board[i][j] == 1: |
| 75 | + print("Q", end = " ") |
| 76 | + else : |
| 77 | + print(".", end = " ") |
| 78 | + print() |
| 79 | + |
| 80 | +#n=int(input("The no. of queens")) |
| 81 | +n = 8 |
| 82 | +board = [[0 for i in range(n)]for j in range(n)] |
| 83 | +solve(board, 0) |
| 84 | +print("The total no. of solutions are :", len(solution)) |
0 commit comments