Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. # Python3 program to solve N Queen
  2. # Problem using backtracking
  3. global N
  4. N = 4
  5.  
  6. def printSolution(board):
  7. for i in range(N):
  8. for j in range(N):
  9. print (board[i][j], end = " ")
  10. print()
  11.  
  12. # A utility function to check if a queen can
  13. # be placed on board[row][col]. Note that this
  14. # function is called when "col" queens are
  15. # already placed in columns from 0 to col -1.
  16. # So we need to check only left side for
  17. # attacking queens
  18. def isSafe(board, row, col):
  19.  
  20. # Check this row on left side
  21. for i in range(col):
  22. if board[row][i] == 1:
  23. return False
  24.  
  25. # Check upper diagonal on left side
  26. for i, j in zip(range(row, -1, -1),
  27. range(col, -1, -1)):
  28. if board[i][j] == 1:
  29. return False
  30.  
  31. # Check lower diagonal on left side
  32. for i, j in zip(range(row, N, 1),
  33. range(col, -1, -1)):
  34. if board[i][j] == 1:
  35. return False
  36.  
  37. return True
  38.  
  39. def solveNQUtil(board, col):
  40.  
  41. # base case: If all queens are placed
  42. # then return true
  43. if col >= N:
  44. return True
  45.  
  46. # Consider this column and try placing
  47. # this queen in all rows one by one
  48. for i in range(N):
  49.  
  50. if isSafe(board, i, col):
  51.  
  52. # Place this queen in board[i][col]
  53. board[i][col] = 1
  54.  
  55. # recur to place rest of the queens
  56. if solveNQUtil(board, col + 1) == True:
  57. return True
  58.  
  59. # If placing queen in board[i][col
  60. # doesn't lead to a solution, then
  61. # queen from board[i][col]
  62. board[i][col] = 0
  63.  
  64. # if the queen can not be placed in any row in
  65. # this colum col then return false
  66. return False
  67.  
  68. # This function solves the N Queen problem using
  69. # Backtracking. It mainly uses solveNQUtil() to
  70. # solve the problem. It returns false if queens
  71. # cannot be placed, otherwise return true and
  72. # placement of queens in the form of 1s.
  73. # note that there may be more than one
  74. # solutions, this function prints one of the
  75. # feasible solutions.
  76. def solveNQ():
  77. board = [ [0, 0, 0, 0],
  78. [0, 0, 0, 0],
  79. [0, 0, 0, 0],
  80. [0, 0, 0, 0] ]
  81.  
  82. if solveNQUtil(board, 0) == False:
  83. print ("Solution does not exist")
  84. return False
  85.  
  86. printSolution(board)
  87. return True
  88.  
  89. # Driver Code
  90. solveNQ()
  91.  
  92. # This code is contributed by Divyanshu Mehta
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement